我有兩個班級(汽車和公共汽車),如下所示
具有相同的屬性(名稱)
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 個不同的類,如何按名稱屬性按字母順序排列陣列?
uj5u.com熱心網友回復:
一種選擇是讓類實作一個通用介面:
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.
}));
uj5u.com熱心網友回復:
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520868.html
標籤:爪哇安卓数组排序目的
上一篇:java-如何呼叫類共享的方法而不首先在Java中強制轉換出Object超類
下一篇:無法在物件中添加屬性
