Еще один вариант с Generics:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GenericComparator<T> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
int price1 = 0;
int price2 = 0;
try {
Method m1 = o1.getClass().getDeclaredMethod("getPrice", o1.getClass().getClasses());
price1 = (int) m1.invoke(o1);
Method m2 = o2.getClass().getDeclaredMethod("getPrice", o1.getClass().getClasses());
price2 = (int) m2.invoke(o2);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return price1 - price2;
}
public static void main(String[] args) {
List<Showroom> showRoomList = new ArrayList<Showroom>();
showRoomList.add(new Showroom("IPHONE", 9000, 4, 4));
showRoomList.add(new Showroom("SAMSUNG", 5000, 4, 4));
showRoomList.add(new Showroom("MOTO", 8000, 4, 4));
showRoomList.add(new Showroom("SONY", 7000, 4, 4));
List<Universal> universalList = new ArrayList<Universal>();
universalList.add(new Universal("IPHONE", 100000, 4, 4));
universalList.add(new Universal("SAMSUNG", 222222, 4, 4));
universalList.add(new Universal("MOTO", 44444, 4, 4));
universalList.add(new Universal("SONY", 7055500, 4, 4));
System.out.println("Showroom");
Collections.sort(showRoomList, new GenericComparator<Showroom>());
for (Showroom s : showRoomList) {
System.out.println(s.getPrice());
}
System.out.println("Universal");
Collections.sort(universalList, new GenericComparator<Universal>());
for (Universal s : universalList) {
System.out.println(s.getPrice());
}
}
}
Выход:
Showroom
5000
7000
8000
9000
Universal
44444
100000
222222
7055500
Примечание. Обязательно создайте установщик / получатель для атрибутов в универсальных и демонстрационных залах.