【问题标题】:Java .contains method [duplicate]Java .contains 方法[重复]
【发布时间】:2019-05-09 13:41:04
【问题描述】:

我创建了一个充满“状态”的数组列表,但在添加状态后无法在列表中找到状态

public class State {
    int a;
    int b;
    int c;

    public State(int a,int b,int c) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

然后在主类中

public class Main {
    static ArrayList<State> nodes = new ArrayList<State>();

    public static void main(String[] args) {
      State randomState = new State(12,0,0);
      nodes.add(randomState);
      System.out.println(nodes.contains(new State(12,0,0)));
    }      
}

这将返回 false,但如果我这样做

System.out.println(nodes.contains(randomState));

将返回 true。 任何帮助表示赞赏

【问题讨论】:

    标签: java arrays arraylist methods contains


    【解决方案1】:

    List.contains() 依赖于对象的equals() 方法:

    更正式地说,返回 true 当且仅当此列表包含 at 至少一个元素 e such that (o==null ? e==null : o.equals(e)).

    State 类中覆盖它和hashCode(),例如:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof State)) return false;
        State state = (State) o;
        return a == state.a &&
                b == state.b &&
                c == state.c;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(a, b, c);
    }
    

    或者不要使用这种方法,自己进行搜索。
    例如:

    public boolean isAnyMatch(List<State> states, State other){   
      return states.stream()
                   .anyMatch(s -> s.getA() == other.getA() && 
                             s.getB() == other.getB()  && 
                             s.getC() == other.getC() )
    }
    
    
    System.out.println(isAnyMatch(nodes, new State(12,0,0));
    

    【讨论】:

    • 你,你知道如何欢迎你的配对:)
    猜你喜欢
    • 2015-07-03
    • 2014-08-20
    • 2019-05-03
    • 2013-12-02
    • 2020-04-08
    • 2013-07-05
    • 2017-08-31
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多