Arraylist - 如何获得特定的 element/name?

Arraylist - how to get a specific element/name?

我尝试搜索 WWW 但没有找到答案。在这里也找不到。

这是我的问题: 如何从 ArrayList 中的客户那里获取特定名称(元素?)? 我想象它看起来像这样:

ArrayList<Customer> list = new ArrayList();

String name = list.get(2) // which would return the Customer at 2's place. 

但是,如果我想按姓名搜索客户怎么办,比如说一个名叫 Alex 的客户?我该怎么做?

额外问题:我该如何删除该客户?

使用ArrayList,你必须循环......如果可以,使用Map(HashMap,TreeMap)来快速找到一个元素。 例如,如果您总是按名称搜索,这会起作用。 (使用名称作为地图的关键字)

没有办法明确地做你想做的事,除非你想遍历整个集合,将所需的名称与当前的名称进行比较。如果你想要这种类型的功能,你可以尝试像 HashMap.

这样的地图

正如其他人所说,这并不是那么高效,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;
        }
    }

为 Customer 对象实施 equals 和 hashcode。为此使用客户名称属性。

使用ArrayList.indexof查找元素的索引。使用 Arraylist 中的 remove 方法按索引移除对象。

您将不得不在函数调用中使用类似这样的方法遍历数组。

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。