java - What Is The Difference Between .equals() and ==? -


i read .equals() compares value(s) of objects whereas == compares references (that -- memory location pointed variable). see here: what difference between == vs equals() in java?

but observe following piece of code:

package main;  public class playground {      public static void main(string[] args) {         vertex v1 = new vertex(1);         vertex v2 = new vertex(1);          if(v1==v2){             system.out.println("1");         }         if(v1.equals(v2)){             system.out.println("2");         }     } }  class vertex{     public int id;      public vertex(int id){         this.id = id;     } } 

output:
(nothing)

shouldn't printing 2?

you need implement own .equals() method vertex class.

by default, using object.equals method. from docs, does:

the equals method class object implements discriminating possible equivalence relation on objects; is, non-null reference values x , y, method returns true if , if x , y refer same object (x == y has value true).

you can this:

@override public boolean equals(object obj) {     if (obj == null) return false;     if (obj.getclass() != getclass()) return false;     vertex other = (vertex)obj;     return (this.id == other.id); } 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -