vamsi
vamsi

Reputation: 143

how to know if the map contains that object based on the object properties

I am using a map and want to use a value object as a map key..and a list as value. The value object has 2 properties first name, second name..i want to return map.containsKey() as true if both properties matched by some key in the same map..

I tried to use comparator as below

public class comaparatorEx  implements Comparator<Test>{
    public static void main(String args[]){

        Map m= new HashMap<Test,List<String>>();
        Test t = new Test();
        t.setFirstname("vamsi");
        t.setSecondname("priya");

        List descriptionList=new ArrayList();
        descriptionList.add("description1");
        m.put(t, descriptionList);
        Test t2 = new Test();
        t2.setFirstname("vamsi");
        t2.setSecondname("priya");

        if(m.containsKey(t2)){
            System.out.println("user found");
        }           
    }

    public int compare(Test o1, Test o2) {
    if((o1.firstname.equals(o2.firstname) )&& o1.secondname.equals(o2.secondname))
        return 0;
    else return 1;
    }
}

this is the value object i am using

public class  Test  {

String firstname;
String secondname;

public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getSecondname() {
    return secondname;
}
public void setSecondname(String secondname) {
    this.secondname = secondname;
}

}

But it returns false for me..please help me ..thanks in advance

Upvotes: 4

Views: 5390

Answers (4)

Arvind Sridharan
Arvind Sridharan

Reputation: 4045

you would have to override the default equals method in your test class.

you can write something like this.

@Override
public boolean equals(Object o) {
    if(null != o && o instanceof test && o.attr1.equals(this.attr1)) return true;
    else return false;
}

containskey In map looks at the equals method. More info in the java docs

The implementation of equals i have given is just an example. For a proper implementation you should read this

Upvotes: 0

Bernhard Barker
Bernhard Barker

Reputation: 55609

For a HashMap, you need to overwrite equals and hashCode in your class.

Possible implementation:

class Test
{
  ...
  @Override
  public int hashCode()
  {
     return 31*firstname.hashCode() + secondname.hashCode();
  }

  @Override
  public boolean equals(Object obj)
  {
     // basic type validation
     if (!(obj instanceof Test))
        return false;

     Test t = (Test)obj;
     return firstname.equals(t.firstname) && secondname.equals(t.secondname);
  }
}

Comparator is for comparison-based collections such as TreeMap. To use this, supply an instance of this class in the constructor:

Map m = new TreeMap<Test,List<String>>(new comaparatorEx());

But there is a problem with your compare function - there needs to be logical ordering between the elements (there isn't as you never return -1). String has a compareTo, which you can just use:

public int compare(Test o1, Test o2) {
  int result = o1.firstname.compareTo(o2.firstname);
  if (result == 0)
    return o1.secondname.compareTo(o2.secondname));
  else
    return result;
}

Upvotes: 5

Prabhaker A
Prabhaker A

Reputation: 8473

You need override the hashcode() and equals() methods to give meaningful equality between the Test object.
HashMap insertions is bassed on the hashcode.
When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object and keys equals () method will be used to identify correct key value pair in HashMap .

Read more: http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz2fDozSqmi

Upvotes: 0

James
James

Reputation: 8586

HashMap uses the hashCode() and equals() methods, internally, to determine e.g. what buckets to look in, and whether the objects in that bucket are the same. You will need to implement both for your Test class, otherwise it will effectively default to reference equality (i.e. are they the exact same object)

Upvotes: 0

Related Questions