【问题标题】:How can I access Specifical Data in an object through Generic arrayList?如何通过 Generic arrayList 访问对象中的特定数据?
【发布时间】: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&lt;Car&gt;
  • 我想更了解 Generic,所以我为此目的进行了测试 :(((
  • 您的泛型似乎落后了。通用的意思是“可以接受各种不同(通用)类型内容的数据结构(如列表或集合)”;您似乎正在寻找 CompositeDelegate 模式。

标签: java object generics arraylist


【解决方案1】:

T 可以是GenericCar&lt;T&gt; 中的任何类,而不仅仅是 Car,因此编译器不知道“getName”指的是 Car 中的方法。

这是修复它的一种方法。您可以为类型变量使用 bound 来告诉编译器 T 实际上必须是某种 Car:

class GenericCar<T extends Car>

【讨论】:

  • 感谢您的回答,我真的需要这个!
  • ...感谢您的回答,我真的需要这个!...“-@DEV-WEB,我很好奇。您不接受 Joni 的回答的原因是什么?提前致谢。
猜你喜欢
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 2018-06-28
  • 1970-01-01
  • 2011-09-18
  • 2015-10-07
相关资源
最近更新 更多