0

I have an arraylist of custom object.

CustomObject:

public class CustomObject 
 {
private String name ;
private int isCorrcet ;
private int icon;
private int disableIcon;
}

For ArrayList having boolean Object we can check whether any boolean object exists having value true.

arrayList.contains(true);

how we can do this for custom object.check whether custom object exists whose data Member isCorrect having value 1.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user3586231
  • 391
  • 4
  • 21
  • `contains()` depends on `equals()`, so you can only do so if you have `equals()` depend only on `isCorrect`, which probably isn't ideal for you. – awksp May 21 '14 at 09:37
  • when i use arrayList.contains(new CsustomObject()); the Custom object contain method work fine. but when i use arrayList.contains("Name"); CustomObject contain method does not work .can any body explain why. – user3586231 May 21 '14 at 20:17
  • Well, a `String` isn't a `CustomObject`. So of course `contains()` should return `false`. – awksp May 21 '14 at 20:27

3 Answers3

1

Override Equals and hashCode. Here is an example

 public final class MethodName {
        private final String name;
        private final String mobile;

    public MethodName(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }

    public String getName(){
        return name;
    }

    public String getMobile(){
        return mobile;
    }

    @Override
    public boolean equals(Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
      result = false;
    } else {
      MethodName method = (MethodName) object;
      if (this.name == method.getName()
          && this.mobile == mobile.getMobile()) {
        result = true;
      }
    }
    return result;
    }

    @Override
    public int hashCode() {
    int hash = 3;
    hash = 7 * hash + this.name.hashCode();
    hash = 7 * hash + this.mobile.hashCode();
    return hash;
   }
  }
user1211
  • 1,507
  • 1
  • 18
  • 27
Vinnie
  • 452
  • 5
  • 24
0

You have to override and implement equals and hashcode method for your object.

You can find more details about it in the below post. What issues should be considered when overriding equals and hashCode in Java?

contains() method works on the equals/hashcode implementation of the object. Basically it will iterate over the entire list passing each item of the list to the equals method of the object which you pass as a parameter to the 'contains' method.

Community
  • 1
  • 1
Dev Blanked
  • 8,555
  • 3
  • 26
  • 32
  • `contains()` only depends on `equals()`. You can survive without `hashCode()`, although it isn't recommended to override one but not the other. – awksp May 21 '14 at 09:40
0

You would need to override equals and hashcode method in your custom object and then use contains on Arraylist.

Ashish
  • 85
  • 1
  • 1
  • 11