【发布时间】:2013-05-22 00:50:02
【问题描述】:
假设我有一个 ArrayList,其中填充了不同类型的对象...
ArrayList<Fruit> shelf = new ArrayList<Fruit>();
Apple apple = new Apple();
Orange orange = new Orange();
Pear pear = new Pear();
shelf.add(apple);
shelf.add(orange);
shelf.add(pear);
我想知道shelf 是否包含Orange 对象。我试过了
shelf.contains(Orange.class)
但这不会返回 true。我的理解是contains使用equals方法进行对象比较,所以我不知道为什么会这样。
我意识到我可以简单地遍历 ArrayList 并单独检查对象的类型,但我很好奇为什么 contains 的行为不符合我的预期。
【问题讨论】: