Reputation: 23
I am currently working on a project in java. I need to create a method that compares two items by name. My first file is called Item
which has a name. The second file has an arrayList
of Items
. I need to create an equal method which compares two items based on their name. I need to return a boolean
and the code starts with this.
public boolean toEqual(Object o)
I am confused about what to do next. I know you will probably have to use an if else statement as well as the getName()
method I created. However I think am supposed to cast the object as an Item object but I don't know how. Can anyone suggest anything? Thanks.
Upvotes: 2
Views: 204
Reputation: 582
Let's say you have a class called Item
And your Item
class have an instance field called name
which you use it to store the name of the item.
class Item {
private String name = "item name";
public String getName() {
return name
}
public boolean toEqual(Object o) {
// Firstly cast it to Item
Item item = (Item) o;
// Then perform the compare
return (name.equals(item.getName()));
}
}
Actually you can change the signature of toEqual
method to
public boolean toEqual(Item o)
. In this case you will not need the cast operation.
public boolean toEqual(Item o) {
// Perform the compare
return (name.equals(o.getName()));
}
Upvotes: 0
Reputation: 7259
You are correct on what to do, and so now you just need to put it together.
http://www.javabeginner.com/learn-java/java-object-typecasting That site has some info on casting objects in Java. Basically to case one object to another, you do something like this:
Item i = (Item) o;
That will cast your o
to type Item
Next you need to see if i.getName().equals(getName())
. You can return that result and you should be done :)
Good luck!
Upvotes: 2
Reputation: 7736
You should implement the boolean equals(Object)
and int hashCode()
for the item class, because then you can simply invoke the contains(Object) method of the list to find if a matching item exists in the list.
Upvotes: 0
Reputation: 1836
You can cast object like this -
(ClassName)obj
However, a much better approach would be to override equals & hashcode methods of java.lang.Object and handle it there. To know how to override it correctly, you can refer to this article - http://www.technofundo.com/tech/java/equalhash.html
HTH, - Manish
Upvotes: 1