+ 1
Writing an equals method to compare two objects's contents - Java
Could someone explain the line 73, 74 in this code for me? I don't understand what is this "object2.symbol" means in the code. - Thank you in advance! https://code.sololearn.com/cHuxcV55TB89/#java
8 Answers
+ 6
The class Stock has two attributes:
String symbol;
double sharePrice;
Lets say you have two objects:
Stock a and Stock b.
a has its own String symbol
b has its own String symbol
Same for sharePrice.
Now you call a.equals(b).
To compare two Strings use equals(). double is primitive, here you can use ==.
a is the object which calls the method, b is the parameter.
Inside the method b gets object2
//btw: I prefer to use the keyword this
this.symbol.equals(object2.symbol) && this.sharePrice == object2.sharePrice
-> a.symbol equals b.symbol AND
a.sharePrice equals b.sharePrice?
->if yes return true, else return false
Hope it is not too confusing ;)
+ 4
LeoBeliik
equals() is a method which all objects inherits from the Object class.
You can also use equals() to compare two Lists, Arrays or whatever
Also if you write own classes your objects has an equals() method. But you have to override it, if you want to use it.
+ 2
coip
symbol and share price are private. To get access to the values you have to use the getters.
getSymbol() and getSharePrice()
In another class:
Stock s = new Stock("abc", 1.2)
String symbol = s.getSymbol();
double sharePrice = s.getSharePrice();
+ 1
coip
About this: https://www.javatpoint.com/this-keyword
getters/setters: https://www.sololearn.com/learn/Java/2154/
+ 1
Thank you Denise RoĂberg. I already know about Getters and Setter. I just want to know about wht this syntax means: instance.nameOfField (eg: object2.symbol).
+ 1
coip
instance = object of a class
fields = attributes
object2 is an instance of class Stock
symbol is the name of the field.
+ 1
you should have to overload hashcode() method and equals() method
0
Thanks Denise for your reply. I havenât learned the keyword this yet. Iâve a questions also. If I want to access a private field (e.g., symbol and sharePrice) in another class, should I write an instance of this class followed by a dot and the name of the field?