首页 > 解决方案 > 如何将多个类添加到 Generic ArrayList?

问题描述

我正在做一项作业,我只能将特定类添加到通用 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 语句无法正常工作,因为它在我测试时不断被触发。

标签: javagenericsarraylist

解决方案


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

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

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


推荐阅读