How to sort 3 parallel arrays?

Currently, I have 3 arrays of information and I'm not sure how to sort them based on one of the values:

int[] rank = { 1, 3, 4, 2, 5 }; String[] game = { "Snake", "Mines", "Fragged", "Siege", "Tower" }; int[] year = { 1980, 1983, 1981, 1995, 1992 }; 

I want to sort it by rank, and I saw many examples of using comparators to sort 2 parallel arrays, but I did not see any example for sorting more than 2.

My first thought was to create a class with a variable for each, and then sort this object, but is this an additional class that is really needed for sorting?

+4
source share
3 answers

My first thought was to create a class with a variable for each, and then sort this object, but is this an additional class that is really needed for sorting?

This is not strictly necessary - you could definitely write code to avoid it if you really wanted to. However, I would say that this is good.

You actually do not have three collections of individual elements: you have one set of elements, each of which has three properties. So make your code appropriate. Whenever you find that you have parallel collections, such as a[0] linked to b[0] , linked to c[0] , etc., you should consider encapsulating this information in a separate class. This will make your code much easier to maintain and provide more consistency.

For example, for these arrays, it makes no sense to have different lengths: but there is nothing in the declaration to stop it. If you have one collection, you cannot have different numbers of elements for different properties, precisely because you have one collection.

+10
source

I think creating a new class would be the cleanest solution. You can manually implement the new sort function to duplicate swaps to the other 2 arrays when you apply the swap to the first array (rank), but it gets messy very quickly.

You will need the following:

 public class Game implements Comparable<Game>{ private int rank = 0; private int year = 0; private String name = ""; ... // Constructor + // Usual getters and setters here .. public int compareTo(Game anotherGame) { return this.rank - anotherGame.getRank(); } } 

And then you can just do:

 List<Game> games = new ArrayList<Game>(); ... // Add some games to your games list ... Collections.sort(games); 
+3
source

Is an extra class needed? Well no, of course not. You can come up with a sorting procedure that preserves all consistency. However, what happens if you decide next week that you need a 4th array, such as a publisher? Now your sorting procedure will not work, and you should write a new one.

If you instead write a class to store these fields as properties, you can greatly simplify the sorting logic, plus you only need to worry about a single array. Any additional work that you are currently doing will pay off very quickly, and then the next time you support this code.

+2
source

Source: https://habr.com/ru/post/1447055/


All Articles