Reputation: 742
I'm trying to find an object in the List collection by his name using Contains method, but, somehow, it doesn't work. How should I use it?
This is how I try to use this
CandyDao.getAllCandys().contains("Caramel")
But it can't find an object which I need.
CandyDao.java
public class CandyDao {
private List<Candy> candys = Arrays.asList(new Candy("Caramel", 3, false),
new Candy("Marmelade", 2, true));
public List<Candy> getAllCandys(){
return candys;
}
}
Candy.java
public class Candy {
private String name;
private float price;
private boolean InStock;
public Candy() {
}
public Candy(String name, float price, boolean InStock) {
setName(name);
setPrice(price);
setInStock(InStock);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public boolean getInStock() {
return InStock;
}
public void setInStock(boolean InStock) {
this.InStock = InStock;
}
}
Upvotes: 1
Views: 287
Reputation: 159260
Since the list contains Candy
objects, the contains()
method needs a Candy
object for the comparison, so you can't use contains("Caramel")
.
To check if the list contains a Candy
object with a name
of "Caramel"
, you can use Java 8+ Streams to do the search:
CandyDao.getAllCandys().stream().Map(Candy::getName).anyMatch("Caramel"::equals);
The equivalent non-stream version would be:
boolean hasCaramel = false;
for (Candy candy : CandyDao.getAllCandys()) {
if ("Caramel".equals(candy.getName())) {
hasCaramel = true;
break;
}
}
Upvotes: 3
Reputation: 3433
getAllCandys()
method returns a list of Candy
objects. You should look each element's name
property on the list. So c
is an element of candys
list. Use c.getName().contains("Caramel")
to look for "Caramel"
for(Candy c : candys) {
System.out.println(c.getName() + " contains? " + c.getName().contains("Caramel"));
}
Upvotes: 0
Reputation: 16053
Override the equals
& hashcode
method like below :
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Candy candy = (Candy) o;
return Objects.equals(name, candy.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
Now, Since the equals function only checks name for equality of Candy
object, the following should work:
CandyDao.getAllCandys().contains(new Candy("Caramel", 0, true)) . //2nd & 3rd arg of Candy constructor are inessential/dummy
Upvotes: 2
Reputation: 1239
You should override the Object#equals
method in Candy
as shown below:
@Override
public boolean equals(Object o) {
if (!(o instanceof Candy)) {
return false;
}
Candy that = (Candy) o;
return Objects.equals(that.getName(), this.getName());
}
After overriding, List#contains
should return true
if the name matches.
Upvotes: 0