【问题标题】:How to determine which objects are stored in an arraylist?如何确定哪些对象存储在 arraylist 中?
【发布时间】:2021-09-18 01:42:28
【问题描述】:

如果我有 3 个名为 CPU、GPU、RAM 的类,并且我将这些类存储到数组列表中 ArrayList<Object> stock = new ArrayList<>() 您可以使用什么方法来返回哪个类存储在某个索引中。例如

stock = new ArrayList<>;
stock.add(new CPU());
stock.add(new GPU());
//method to determine which class is in index 0 
System.out.println(method);
Output: class packageName.CPU

【问题讨论】:

  • 鉴于您的inheritance 标签,我想您的最终解决方案是创建一个名为Chip 的接口或抽象类,CPUGPUMemory 类从中实现/延长。然后:List&lt; Chip &gt; chips = new ArrayList&lt;&gt;();chips.add( new CPU() ) ;

标签: java oop inheritance collections


【解决方案1】:

只有第一个元素

您可以简单地获取元素 0,然后是类,最后是它的名称。

ArrayList<Object> stock = new ArrayList<>();

class CPU{};
class GPU{};

stock.add(new CPU());
stock.add(new GPU());

System.out.println(stock.get(0).getClass().getName());

输出就是你想要的:

com.example.example.model.CPU

所有元素

如果您需要所有类,只需在过程中添加一个 foreach:

stock.forEach(i -> {
    System.out.println(i.getClass().getName());
});

com.example.example.model.CPU

com.example.example.model.GPU

【讨论】:

    【解决方案2】:

    使用标记空间指出的stock.get(index).getClass(),这是一种可怕的做法,最好有一个基本接口。

    【讨论】:

    • 然而这是不好的做法。您的列表应采用 Stock 对象 (ArrayList&lt;Stock&gt;),而 CPU 等类应扩展 Stock (public class GPU extends Stock { ...)。 Stock 应该定义您使用的常用方法,例如 getName()getPrice(),而不是确定确切的类型。
    • 是的,这是不好的做法,将编辑帖子以使其清楚(认为这很明显,哈哈)
    • 是的,对不起,我实际上是在评论 OP 的评论,但他们在我完成输入之前删除了它。
    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多