提问人:seba123neo 提问时间:10/21/2022 最后编辑:Jensseba123neo 更新时间:10/21/2022 访问量:54
对不同类型对象的数组进行排序
Sort array of different types of objects
问:
我有两个班级(汽车和公共汽车),如下所示
具有相同的属性(名称)
第 1 类
class Car {
public String name;
}
第 2 类
class Bus {
public String name;
}
我有两个类的对象数组
ArrayList<Object> vehicles = new ArrayList<>();
vehicles.add(new Car("Fiat"));
vehicles.add(new Car("Citroen"));
vehicles.add(new Bus("Ford"));
vehicles.add(new Bus("Toyota"));
如果数组是 2 个不同的类,如何按 name 属性的字母顺序对数组进行排序?
答:
3赞
knittl
10/21/2022
#1
一种选择是让类实现一个通用接口:
interface NamedVehicle {
String getName();
}
class Car implements NamedVehicle {
public String name;
@Override public String getName() { return name; }
}
class Bus implements NamedVehicle {
public String name;
@Override public String getName() { return name; }
}
然后存储接口引用列表,而不是:Object
final List<NamedVehicle> vehicles = new ArrayList<>(Arrays.asList(
new Car("Fiat"),
new Car("Citroen"),
new Bus("Ford"),
new Bus("Toyota")
));
vehicles.sort(Comparator.comparing(NamedVehicle::getName));
以上是推荐的选项(关键字“针对接口的程序”、“信息隐藏”、“不公开字段”)。如果你不能引入一个界面,它会更加棘手和丑陋,但它是可行的。
final List<Object> vehicles = new ArrayList<>(Arrays.asList(
new Car("Fiat"),
new Car("Citroen"),
new Bus("Ford"),
new Bus("Toyota")
));
vehicles.sort(Comparator.comparing(o -> {
if (o instanceof Car) { return ((Car)o).name; }
if (o instanceof Bus) { return ((Bus)o).name; }
return ""; // you cannot guarantee that the list will only contain Buses and Cars (it is <Object>, after all), so you have to return some dummy value here or throw an exception.
}));
1赞
Adin D
10/21/2022
#2
class Car extends Vehicle {
public Car(String name) {
super(name);
}
}
class Bus extends Vehicle {
public Bus(String name) {
super(name);
}
}
class Vehicle {
public String name;
public Vehicle(String name) {
this.name = name;
}
public Vehicle() {
}
}
ArrayList<Vehicle> vehicles = new ArrayList<>();
vehicles.add(new Car("Fiat"));
vehicles.add(new Car("Citroen"));
vehicles.add(new Bus("Ford"));
vehicles.add(new Bus("Toyota"));
vehicles.sort(Comparator.comparing(vehicle -> vehicle.name));
评论