java - Sorting Polymorphic Arrays -
lets have 3 classes (passenger,pilot,stewardess) inherit abstract class called persons, , in array of persons save many of these objects 3 classes defined, want sort objects inside array of persons in following order:
-all objects class passenger
-all objects class pilot
-all objects class stewardess
is there way achieve without arraylists?
arrays.sort(personarray, new comparator<person>() { @override public int compare(person p1, person p2) { int person1index = getorderindex(p1); int person2index = getorderindex(p2); if (person1index < person2index) { return -1; } else if (person1index > person2index) { return 1; } else { return 0; } } private int getorderindex(person p) { if (p == null) { return 0; } else if (p instanceof passenger) { return 1; } else if (p instanceof pilot) { return 2; } else if (p instanceof stewardess) { return 3; } else { throw new runtimeexception("unexpected person type: " + p.getclass().getname()); } } });
Comments
Post a Comment