0

i'm curently developing app which has lots of ArraYlists and it needs to compare them with nonlist data. When i try this method fdata.contains(data2) it always returns false. ArayLists contains class named 'favdat' which looks like this:`

public class favdat {
    public String product,term,note,link;
}

And Data2 is defined like this: favdat Data2=new favdat(); I have also tryed retain all method and it returns list in the size of 0. I know that some data are equal.

So the question is how could i tell if fdata contains data2?

J1and1
  • 920
  • 3
  • 12
  • 25

2 Answers2

9

The default implementation to compare objects is to compare if they are the same object, so two objects with the exactly same attributes would still not be equals. What you need to do is override the hashCode and equals methods. As an example:

public int hashCode() {
    return product.hashCode() * 31 + term.hashCode();
}

public boolean equals(Object o) {
    if (o instanceof favdata) {
         favdata other = (favdata) o;
         return product.equals(other.product) 
             && term.equals(other.term) 
             && note.equals(other.note) 
             && link.equals(other.link);
    } else {
        return false;
    }
}

In java classnames are usually started with capitals, so it would be Favdat, and your code usually gets easier to read to keep the field declarations separate.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
1

You need to define a method called equals(Object obj) inside favdat that will enable object comparison.

Here's a more detailed howto:

Community
  • 1
  • 1
ariefbayu
  • 21,849
  • 12
  • 71
  • 92