Today, using the Caontains method of the ArrayList class is a problem, I wrote a ArrayList that holds the user class but always returns False when List.contains (user) is called. To see the next ArrayList source code, the source code is as follows:
Public Boolean contains (object o) {return indexOf (O) >= 0, } public int indexOf (object o) {if (o = = null) {for (int i = 0; i < size; i++) if (elementdata[i]==null) return i;} else {for (int i = 0; i < size; i++) if (O.E Quals (Elementdata[i]) return i;} return-1; }
The Contains method is found to invoke the O.equals (Elementdata[i]) method, where Elementdata[i] is an instance of the object class. That is to say, I actually compare user.equals (object) When I call List.contains, which of course returns false.
Correct method, rewrite the Equals method in the user class. The code is rewritten as follows:
Publicboolean equals (Object obj) { if (obj instanceofuser) { User U = (user) obj; Returnthis.username.equals (u.username) &&this.password.equals (password); } Returnsuper.equals (obj); }
From for notes (Wiz)
The Contains method of ArrayList