Let’s say I have a class called Unit (with a position variable x) and extend the class to UnitA, UnitB, UnitC, etc..
this is something I came up with:
Unit[] ordered = new Unit[a_num+b_num+c_num];
ordered = Arrays.copyOf(a_units, a_num); //and add b_units, c_units, etc
Arrays.sort(ordered); //sort using compareTo method
- For best performance and neat programming, what is the best way to sort these values from left to right (the x variable)?
- When the array is sorted, in order to access unit specific variables, how do I find out what type of object each entry is?
Arrays.sort(ordered)will sort based on the natural ordering (defined by the compareTo method) of the units. If the natural ordering is not what you want, then useArrays.sort(array, Comparator)and pass a comparator which compares the position of the units.Regarding your second question: you shouldn’t have to know the type of the units. Your Unit class should provide polymorphic methods that you can call and which are implemented by every subclass to do the appropriate thing. There’s always the
instanceofoperator and thegetClass()method, but using them shows a lack of OO design, and is thus bad practice.