• Post Reply Bookmark Topic Watch Topic
  • New Topic

object Comparision wtih equals  RSS feed

 
Ramakrishna Konanki
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Value {
int i ;
}
public class Equalscomp {
public static void main(String []args) {
Value vl = new Value();
Value v2 = new Value();
vl.i = 100;
v2.i = 100;
System.out.println(vl.equals("v2"));
}
}

here i am geting result as false...
why......................

previous i have studied == is comparing references.
.equals() compares values.....
so what abt the above code..

please explain
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
.equals() compares values...if you have overridden it to compare values. The default version in Object compares references. Lots of common classes, such as String, have overridden it. But if you want to create your own classes and compare values you'll have to override it yourself.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags when posting code. It makes it so much easier to read.

The class Value doesn't override the object implementation of equals. Therefor it will only return true if you're comparing to the same object e.g. == return true.
Secondly you're parsing a String "v2" instead of the object in the equals method.
 
Ninad Kuchekar
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The equals() method accepts an Object as a parameter and you are passing v2 as a String by mentioning it in quotes.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And it's weird to name one variable "vl" (that's a lower-case L) and one "v2"--seems like it'd make more sense to use v1 and v2. But that might just be me.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!