我试图搜索WWW但未能找到答案。在这里也找不到。
这是我的问题: 如何从ArrayList中的Customer获取特定名称(元素?)? 我想它看起来像这样:
ArrayList<Customer> list = new ArrayList();
String name = list.get(2) // which would return the Customer at 2's place.
但是,如果我想通过名字搜索客户,我们可以说客户名为Alex?我该怎么做?
奖金问题:我如何删除该客户?
答案 0 :(得分:3)
正如其他人所说,这并不是那么有效,而HashMap会给你快速查找。但是如果你必须迭代列表,你会这样做:
String targetName = "Jane";
Customer result = null;
for (Customer c : list) {
if (targetName.equals(c.getName())) {
result = c;
break;
}
}
如果需要在迭代时从列表中删除项目,则需要使用迭代器。
String targetName = "Jane";
List<Customer> list = new ArrayList<Customer>();
Iterator<Customer> iter = list.iterator();
while (iter.hasNext()) {
Customer c = iter.next();
if (targetName.equals(c.getName())) {
iter.remove();
break;
}
}
答案 1 :(得分:2)
你将不得不在函数调用中使用类似的东西迭代你的数组。
void int HasName(string name){
for(int i=0; i < list.size(); i++) {
String s = list.get(i).getName();
//search the string
if(name.equals(s)) {
return i
}
}
return -1
}
如果你真的需要按名称搜索,请考虑查看HashMap。
答案 2 :(得分:1)
使用ArrayList,您必须循环...如果可以,使用Map(HashMap,TreeMap)快速查找元素。 例如,如果你总是通过名字寻求,这是有效的。 (使用名称作为地图的关键字)
答案 3 :(得分:1)
除非您想要遍历整个集合,将所需名称与当前名称进行比较,否则无法明确地执行您想要的操作。如果您需要此类功能,可以尝试使用HashMap
等地图。
答案 4 :(得分:0)
为Customer对象实现equals和hashcode。使用客户名称属性。
使用ArrayList.indexof查找元素的索引。使用Arraylist中的remove方法按索引删除对象。