Java arraylist索引
这是我的班级animals.java
:
public class animals {
String Name, ID;
static ArrayList<animals> animalData = new ArrayList<animals>();
public animals(){}
public animals(String name, String id){
super();
this.Name = name;
this.ID = id;
}
public void addAnimal(String name, String id){
animalData.add(new animals(name, id));
}
public int search(String name){
return this.animalData.indexOf(name);
}
}
当我添加带有id的动物名称时,它正常工作,但当我使用搜索方法时,我只看到-1。也许我尝试在这个类中重写方法equals
或indexof
?帮我做这个
谢谢你,很抱歉我的英语不好
# 1 楼答案
您需要定义一个“equals”方法
# 2 楼答案
是的,在集合中使用对象并基于对象执行查找时,需要重写
equals()
和hashcode()
方法indexOf()
返回对象,因为它只返回该特定索引处的对象。但是,当您执行基于对象的查找时,如果没有覆盖equals()和hashCode()
,则equals()
可能会失败,并得到不可预测的结果# 3 楼答案
你在找一根绳子。。。 你最好用一个HashMap我想
但是你必须改变你的结构(这不是很有效)
# 4 楼答案
您正在将
animals
的实例添加到列表中。您正在按名称搜索实例。由于animalData
不包含任何String
的实例,因此indexOf()
永远不会返回索引如果要通过名称访问
animals
的实例,应使用Map<String,animals>
indexOf()
的正确用法是传入一个等于集合中已有实例的实例。正如其他人所指出的,这将需要您定义equals()
来定义使两个实例相等的因素。在重写equals()
时,还应该重写hashcode()
,因为存在假定的相关性注意:惯例是使用大写字母作为类名。此外,类名不应为复数。您将有许多
Animal
的实例,稍后可以创建一个类,该类是Aniamal
的集合,但不应是主类的名称# 5 楼答案
以下是我将使用的代码:
这样,您可以使
search
方法更快(O(1)),不再需要重写equals
方法注意,如果^ {< CD3>}是静态的,则应该考虑使^ {CD4>}静态,因为它是^ {CD5>}的“设置器”。