java - 如何将多个类添加到 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 语句无法正常工作,因为它在我测试时不断被触发。
解决方案
你的主要问题是你搞砸了你的 isinstance 检查。该方法反过来起作用;您正在寻找的是:
ComputerPart.class.isInstance(t)
,不是t.getClass().isInstance(ComputerPart.class)
。但是,您可以更简单地将其写为:t instanceof ComputerPart
.
其次,你搞砸了系统输出。大概你的意思是你的代码中的每个“if”都是一个“else if”,当然第一个除外。
推荐阅读
- reactjs - 默认值或值不适用于 FormItem ANTD
- mongoengine - 棉花糖 EmbeddedDocument 不起作用
- asp.net-core - 如何在 ASP .NET Core 2.1 中更新客户端包?
- node.js - 计算 Observable 完成之前发出的值的数量?
- javascript - Javascript - 使在 eval 或 new Function 中声明的变量进入上下文对象
- apache-kafka - 问题启动模式注册表
- php - mysql DISTINCT GROUP QUERY 我如何列出组
- android - 相对布局:将视图水平和垂直中心与其他视图对齐
- recursion - Prolog - 评估任意大小的表达式
- c++ - 成员和参数存储的常见做法