【发布时间】:2020-11-06 19:53:14
【问题描述】:
这里我有一个关于如何通过通用列表对象访问名为 Car 的对象内的特定数据的问题
-这是我的课Car.java
public class Car {
public String name;
public double price;
public String production;
public Car(String name,double price,String pro){
this.name=name;
this.price=price;
this.production=pro;
}
public String getName(){return this.name;}
public double getPrice(){return this.price;}
public String getProduction(){return this.production;}
}
*我想通过 DisplayCarName() 方法通过泛型访问 Car 对象的 name,但是发生了错误,编译失败在 "u. get(i).getName();"
-这是我的 GenericCar.java
public class GenericCar <T> {
List<T>u ;
GenericCar(){
u = new ArrayList<T>();
}
public void Add(T x){
u.add(x);
}
//i want to display only Car class,specifically name of car,but it seems not work!
public void DisplayCarName(){
for(int i=0;i<u.size();i++){
System.out.println(u.get(i).getName());
}
}
}
*在我的 Main 类中,我不能在泛型类中使用此方法 car2.DisplayCarName();
public class Main() {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
GenericCar<Car>car2= new GenericCar<Car>();
car2.Add(new Car("Toyota",20.3,"Toyota"));
//use this ok!
System.out.println(car2.u.get(0).getName());
//but this is not!
car2.DisplayCarName();
}
}
*关于我的所有问题都是“如何通过通用列表对象访问名为 Car 的对象内的特定数据,对不起,问题太长了!”
【问题讨论】:
-
您的班级名称
GenericCar没有意义。 “通用汽车”有一个清单?什么的?这怎么不仅仅是List<Car>? -
我想更了解 Generic,所以我为此目的进行了测试 :(((
标签: java object generics arraylist