Reputation: 978
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
Upvotes: 0
Views: 85
Reputation: 691745
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 use Arrays.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 instanceof
operator and the getClass()
method, but using them shows a lack of OO design, and is thus bad practice.
Upvotes: 2
Reputation: 308763
If you have to find out what type of object each entry is, you've done it wrong.
Polymorphism is the only way to go. That's what object-oriented languages are for.
You don't say how you want to sort units. Do you mean physical units, like meters for length, kilograms for mass, seconds for time? If yes, what does "sorting" them mean? You can order them alphabetically, of course, but I don't know how meaningful that is.
What is the "position variable"? Do you mean that you'll have a Unit for lengths with underlying values like meter, foot, angstrom, and furlong in different "positions"? And how will you order them? By popularity? The answer changes depending on whether you're in one of the few countries left that still use British units (e.g. the United States; even England gave up imperial units!) or metric.
Upvotes: 5