0

I create an arraylist full of "states" but can't find states in the list after they have been added

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;
    }
}

Then in the main class

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)));
    }      
}

This would return false but if i do

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

would return true. Any help is appreciated

1 Answers1

4

List.contains() relies on the equals() method of the objects :

More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Override it and hashCode() in the State class such as :

@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);
}

Or don't use this method and perform the search yourself.
For example :

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));
davidxxx
  • 125,838
  • 23
  • 214
  • 215