mardi 11 juillet 2017

Why we not need to implement hashcode() and equals() contract on ArrayList and TreeSet and various classes?

According to the hashCode implemetation:- please find below class code :-

public class obj
  {
    int Id;
    String name;
    public obj(String name,int id)
     {
         this.id=id;
         this.name=name;
     }
  }

And create a ArrayList and place some objects in it :-

public static void main(String[] args) {
        ArrayList arrList=new ArrayList<obj>();
        obj obj1=new obj("Hassu",1);
        obj obj2=new obj("Hoor",2);
        obj obj3=new obj("Heniel",3);
        obj obj4=new obj("Hameed",4);
        obj obj5=new obj("Hassu",1);
        arrList.add(obj1);
        arrList.add(obj2);
        arrList.add(obj3);
        arrList.add(obj4);
        arrList.forEach(n -> System.out.println(n));
    }

It gives me a out put with different Hashcode :-

com.arithmatic.obj@1b3ebeb
com.arithmatic.obj@8c4f57
com.arithmatic.obj@18025c
com.arithmatic.obj@16f27d

now if i implement the hashcode() method in obj class like :-

@Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return 1;
    }

and then im getting the following output :-

com.adp.arithmatic.obj@1
com.adp.arithmatic.obj@1
com.adp.arithmatic.obj@1
com.adp.arithmatic.obj@1

But the name is different :-

Hassu
Hoor
Heniel
Hameed

My questions is why the regardless of storing into the single and multiple bucket based on the hashcode why the output is not override. Why im getting the consistent objects properties. How the implementation of hashcode is not effects the TreeSet and ArrayList

Aucun commentaire:

Enregistrer un commentaire