Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

Java ArrayList Contain always return false although it contain the same value

This is my Hole Class

class Hole {

public  int a;
public  int b;

Hole(int a, int b) {
    this.a = a;
    this.b = b;
}

So i adding an ArrayList that contain several several hole

public void checkPathLoop(int x, int y) {
        //rough code

        ArrayList<Hole> leftFlowInnerHole = new ArrayList<>();


        //left holes rules
        leftFlowInnerHole.add(new Hole(0, 1));
        leftFlowInnerHole.add(new Hole(1, 5));
        leftFlowInnerHole.add(new Hole(5, 4));
        leftFlowInnerHole.add(new Hole(0, 4));

when i add

Hole userInputHole = new Hole(0,1);
System.out.print(leftFlowInnerHole.contain(userInputHole));

it always return false !! it suppose to return true.

Is there anything i miss ??

Thank you in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to override the equals method herited from the Object class (and hence also hashCode to respect the contract, see Why do I need to override the equals and hashCode methods in Java? ) in your Hole class.

Returns true if this list contains the specified element. 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)).

Basically the default equals implementation is an == comparison between the two objects

public boolean equals(Object obj) {
   return (this == obj);
}

Since you created two different objects, while they have the same value as attributes they're two distincts objects and hence this == obj returns false.

If you did :

Hole a = new Hole(0,1);
leftFlowInnerHole.add(a);
System.out.print(leftFlowInnerHole.contains(a));

You'll see that it outputs true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...