【问题标题】:How do I add multiple classes to a Generic ArrayList?如何将多个类添加到 Generic ArrayList?
【发布时间】:2019-05-25 20:59:23
【问题描述】:

我正在做一个作业,我只能将特定类添加到通用 ArrayList,但 ArrayList 似乎没有按预期添加类。

public class ComputerOrder<T extends Product> extends GenericOrder<T> {
private List<T> products;//the list of items

    public void addProduct(T t) {
        if (t.getClass().isInstance(ComputerPart.class)) {
            products.add(t);    
        }
        if (t.getClass().isInstance(Service.class)) {
            products.add(t);   
        }
        if (t.getClass().isInstance(Peripheral.class)) {
            products.add(t);   
        }
        else System.out.println("Not the right type of object.");
   }

主要参数测试:

public static void main(String[] args) {

    ComputerPart c;
    c = new ComputerPart(12);

    ComputerOrder<Product> g3 = new ComputerOrder<>();
    g3.addProduct(c);
    g3.print();

}

预期的结果是 ArrayList g3 能够添加 c,因为它是 ComputerPart 对象的一个​​实例,但 ArrayList 是空的。有人可以解释我的代码做错了什么吗?

注意:“else”语句仅用于测试目的,似乎表明 if 语句无法正常工作,因为它在我测试时不断被触发。

【问题讨论】:

  • 由于您没有使用else if 进行服务和外设检查,因此会过于频繁地触发 println。但这并不能解决主要问题。尝试在每个条件子句中添加 printlns 以帮助弄清楚发生了什么。
  • 即使isInstance 已修复,这对于泛型或面向对象编程来说也是一种糟糕的方式。

标签: java generics arraylist


【解决方案1】:

您的主要问题是您搞砸了您的 isinstance 检查。该方法反过来起作用;您正在寻找的是:

ComputerPart.class.isInstance(t),而不是t.getClass().isInstance(ComputerPart.class)。但是,您可以更简单地写成:t instanceof ComputerPart

其次,您搞砸了系统输出。大概您的意思是将代码中的每个“if”都改为“else if”,当然第一个除外。

【讨论】:

  • 非常感谢,rzwitserloot,t instanceof ... 有效。感谢您的帮助!
猜你喜欢
  • 2022-01-05
  • 2020-11-08
  • 2019-04-10
  • 1970-01-01
  • 2015-12-16
  • 2016-03-08
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多