首页 > 解决方案 > 如何将包含方法与自定义数组列表一起使用?

问题描述

如何使用contains方法仅按 id 搜索,我想在不使用循环的情况下检查 id 是否等于 4,如何?

测试班

public class Test {

    private int id;
    private String name;
    private int age;

    public Test(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

}

设置数据

List <Test> list = new ArrayList <> ();
list.add(new Test(1, "Name 1", 25));
list.add(new Test(2, "Name 2", 37));
list.add(new Test(3, "Name 3", 63));
list.add(new Test(4, "Name 4", 19));
list.add(new Test(5, "Name 5", 56));

标签: java

解决方案


如果您检查 java 库中的 contains 方法。它在内部调用indexOf方法(内部调用方法),它通过对对象indexOfRange进行方法调用来返回索引。equals

int indexOfRange(Object o, int start, int end) {
        Object[] es = elementData;
        if (o == null) {
            for (int i = start; i < end; i++) {
                if (es[i] == null) {
                    return i;
                }
            }
        } else {
            for (int i = start; i < end; i++) {
                if (o.equals(es[i])) {
                    return i;
                }
            }
        }
        return -1;
    }

在您的代码equals中将在Test类对象上调用。

作为解决方案,如果匹配,则覆盖equals要返回的方法。但我会说这不是一个好的解决方案,因为方法应该遵循一些合同。trueidequals

因此,在这里也应该使用StreamsAPI 是正确的(尽管 Stream 也将在内部使用迭代)。

List <Test> list = new ArrayList <> ();
list.add(new Test(1, "Name 1", 25));
list.add(new Test(2, "Name 2", 37));
list.add(new Test(3, "Name 3", 63));
list.add(new Test(4, "Name 4", 19));
list.add(new Test(5, "Name 5", 56));
        
boolean isMatch = arr.stream().anyMatch(i-> i.id == toMatch);

推荐阅读