我有一些类可以实现的接口:
interface Vehicle {}
class Car implements Vehicle {}
class Bicycle implements Vehicle {}
我还有另一个具有此方法的getter和setter的接口:
interface Person {
public ArrayList<Vehicle> getVehicles();
public void setVehicles (ArrayList<Vehicle> vs);
}
一些类实现了它:
class CarOwner implements Person {
public ArrayList<Car> cars;
public ArrayList<Car> getVehicles() {
return cars;
}
public void setVehicles(ArrayList<Car> cars) {
this.cars = cars;
}
}
class BicycleOwner implements Person {
//...
}
但是,它抱怨设置器与接口具有相同的擦除,但没有覆盖它。我必须将to更改ArrayList<Vehicle>
为ArrayList
,并将其强制转换为函数,但是它不是“安全的”(我知道它应该可以工作,但其他人可能不能)。如何处理这种情况?
编辑:
当我将代码更改为答案时,它不再抱怨。但是当我使用它时,例如
//I have an arraylist of Person
ArrayList<Person> persons;
//...
Vehicle first = persons.get(0).getVehicles().get(0);
它抱怨类型的第一行需要一个参数...但是它可以是任何类型的person,因为Arraylist persons
可以包含所有类型的Person。如何执行此操作?还是必须保留它而没有模板参数?
编辑2:
我在那里更新了答案,发现当我打电话给setter时再次引发错误...
Person<?> personA = persons.get(0);
ArrayList<Vehicle> vs = new ArrayList<Vehicle>();
//vs.add(carA);
personA.setVehicles(vs);
最后一行给出错误:This gives error saying The method setVehicles(ArrayList<capture#6-of ?>) in the type Post<capture#6-of ?> is not applicable for the arguments (ArrayList<Vehicle>)
。我尝试更改为,ArrayList<?>
但不起作用...
您的问题是您的接口被声明为接受an ArrayList<Vehicle>
,但是您正在尝试使用采用的方法来实现它ArrayList<Car>
。有人可以调用您的接口,并合法地将其交给其他类型的扩展工具列表,因此您的代码将无法编译。
您想要做的是使您的Person
接口通用,以便它可以采用任何可扩展的类型Vehicle
,然后使之CarOwner
成为实现的类Person<Car>
:
interface Person<T extends Vehicle> {
public ArrayList<T> getVehicles();
public void setVehicles (ArrayList<T> vs);
}
class CarOwner implements Person<Car> {
public ArrayList<Car> cars;
public ArrayList<Car> getVehicles() {
return cars;
}
public void setVehicles(ArrayList<Car> cars) {
this.cars = cars;
}
}
好吧,如果您要使用raw ArrayList<Person>
,那么实际上只是将类型错误从类定义转移到了对它的使用。参数化后Person
,还需要以这种方式使用它:
ArrayList<Person<?>> persons = new ArrayList<>();
// ...
Vehicle first = persons.get(0).getVehicles().get(0);
您可以在此处了解有关Java通配符的更多信息。
是的,通配符的缺点是编译器不知道类型。在这种情况下,您可以只使用Vehicle
接口,因为您确实知道所有内容都在扩展:
ArrayList<Person<Vehicle>> persons = new ArrayList<Person<Vehicle>>();
// ...
Person<Vehicle> personA = persons.get(0);
ArrayList<Vehicle> vs = new ArrayList<Vehicle>();
//vs.add(carA);
personA.setVehicles(vs);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句