Using Contains for objects in List collection - java

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;
}
}

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;
}
}

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

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.

getAllCandys() method returns a list of Candyobjects. You should look each element's nameproperty on the list. So cis an element of candyslist. Use c.getName().contains("Caramel") to look for "Caramel"
for(Candy c : candys) {
System.out.println(c.getName() + " contains? " + c.getName().contains("Caramel"));
}

Related

Java arraylist of objects how to search for elements error

I am trying to Implement a class named Parade using an ArrayList, which will manage instances of class Clown. Each Clown needs to be identified by all object data String for their name, int id and double size. I join a new Clown to the end of the Parade. Only the Clown at the head of the Parade (i.e., the first one) can leave the Parade. In addition, I write a method called isFront that takes a Clown as parameter and returns true if the passed clown is at the front of the parade otherwise returns false. Create a test application to demonstrate building a parade of three or four clowns and include your own name. Then, remove one or two, and add another one or two. Also, test the isFront method by passing different clowns to the method.
I have a code but it is not returning true for the isFront method, I am trying to use contains method I also tried to use Comparable interface Clown but it did not work that well. Not sure what to do.
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Parade circus = new Parade();
circus.addClown(new Clown("Bobby",9,12.0));
circus.addClown(new Clown("Clair", 2, 11.0));
circus.addClown(new Clown("Tony",6,10.0));
circus.addClown(new Clown("Sarah",3,5.0));
circus.display();
System.out.println(circus.isFront(new Clown("Bobby", 9, 12.0)));
}
}
import java.util.ArrayList;
public class Parade
{
private static ArrayList<Clown> parade;
private int top;
public Parade()
{
top=0;
parade= new ArrayList<Clown>();
System.out.println(parade);
}
public void addClown(Clown c)
{
parade.add(c);
top++;
}
public void removeClown() //(Clown c)
{
parade.remove(0);
top--;
}
public void display()
{
System.out.println(parade);
}
public void getData()
{
parade.get(0);
}
public void setData()
{
parade.set(1,new Clown("Claire",2,5.0));
System.out.println(parade);
}
public int getTop()
{
return top;
}
public boolean isFront(Clown c)
{
return !parade.isEmpty() && c.equals(parade.get(0));
}
//exceptions
}
public class Clown
{
private String name;
private int id;
private double size;
public Clown(String name, int id, double size)
{
this.name=name;
this.id=id;
this.size=size;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public double getSize()
{
return size;
}
public String toString()
{
return name.toString() + id + size;
}
public boolean equals(Object o) {
if (o instanceof Clown c) {
return this.getName().equals(c.getName()) && this.getId() == c.getId() && this.getSize() == c.getSize();
}
return false;
}
}
their is not much info in our textbook about this stuff Java FOundations 5th e Lewis like working with objects and arraylists it skips it and assumes you already know it lol..
Firstly, objects in Java are, by default, compared by reference. So, even if you create two Clown objects with the exact same properties, Java sees them as different objects because both those object references are not the same, they are both referring to different memory locations. You can override this behavior and ask Java to compare it as you want by overriding the equals() method of the Object class:
public class Clown {
private String name;
private int id;
private double size;
public Clown(String name, int id, double size) {
this.name=name;
this.id=id;
this.size=size;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double getSize() {
return size;
}
#Override
public boolean equals(Object o) {
if (o instanceof Clown) {
Clown c = (Clown) o;
return this.getName().equals(c.getName());
}
return false;
}
#Override
public int hashCode() {
return this.getId();
}
#Override
public String toString() {
return name.toString() + id + size;
}
}
This will help with contains()(it internally uses equals()).
Secondly, you can just compare your clown with the first clown to see if it is the one at the front:
public boolean isFront(Clown c) {
return !parade.isEmpty() && c.equals(parade.get(0));
}
The isFront() method will return true if the parade is not empty and the clown c is equal to to the first clown in the parade. get(0) retrieves the first clown in the parade.
As per your comment, if you want that two clowns be equal only if all their properties are equal, change your equals method to:
#Override
public boolean equals(Object o) {
if (o instanceof Clown) {
Clown c = (Clown) o;
return this.getName().equals(c.getName()) &&
this.getId() == c.getId() &&
this.getSize() == c.getSize();
}
return false;
}
The equals() method is of the Object class which is the parent class of all Java classes. It defines how to compare two objects.
Its signature is as follows:
public boolean equals(Object obj)
As we're overriding, its signature must be the same in the derived class, in our case in class Clown. Its parameter is of type Object not Clown. Any type can be converted to Object, if I compare an object of Clown to another type, like:
Clown c = new Clown("X", 1, 10);
if ( c.equals(objectOfAnotherType) ) {..}
it will still work.
So we use the instanceof operator to check if that another object is also a Clown. If it is not an instance of Clown, we return false but if it is, we convert/cast that object to Clown, only then we can call getName() and other getter methods:
if (o instanceof Clown) {
Clown c = (Clown) o; //Casting happens here
return this.getName().equals(c.getName()) &&
this.getId() == c.getId() &&
this.getSize() == c.getSize();
}
return false;
Java 14 introduced a shortcut for this, instead of these steps:
if (o instanceof Clown) {
Clown c = (Clown) o;
we can simply write:
if (o instance of Clown c)
which does the casting for us and stores it in c.
Lastly, I have also overriden Object.hashCode() because you have to when you override equals(), here's why.

Check ArrayList for duplicates

Class:
public class Variant
{
private String variant;
private String quantity;
//getters and setters
}
ArrayList:
ArrayList<Variant> variantList = getVariantsList();
Now I want to check whether variantList contains a duplicate entry of variant or not? Please note that variant having two entries with different quantity are to be considered as duplicates.
You can simply ovveride your equals method in your Variant class and provide all the rules for equality in that method.
#Override
public boolean equals(Object obj) {
..
Then you can use contains method or just pass it to a Set, that eliminates all your duplicates.
If you want variant having two entries with different quantity also considered as dup, then you can add that condition in your equals.
Override equals(Object obj) method and try to compare the object on variant and quantity.
Try to loop thru the variantList and do check for duplicity using variantList.contains(variant).
There are two things you need to do:
Override the equals() in your Variant class(minimal code below):
Please note that the below code only checks for quantity and not the variant prop. Your IDE might help you to generate the equals() as well.
#Override
public boolean equals(Object object) {
boolean isEqual = (this == object);
if(object instanceof Variant){
Variant variant = (Variant) object;
isEqual = this.quantity.equals(variant.quantity);
}else{
isEqual = false;
}
return isEqual;
}
Check if the List contains the object - which will use the equals() to check if both are equal.
for (Variant variant : variantList) {
if (variantList.contains(variant)) {
//do logic if its present
}
}
Just check one object with other objects of list
Override equals method in Variant class
#Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof Variant) {
Variant temp = (Variant) obj;
return this.quantity.equals(temp.quantity); //for different quantity
} else {
return false;
}
}
return false;
}
Then check :
for (int i = 0; i < variantList.size(); i++) {
for (int j = 0; j < variantList.size(); j++) {
if (i != j) {
if (iList.get(i).equals(iList.get(j))) {
//logic when duplicate
break;
}
}
}
}
Follow the below guidelines:
Your Class Variant must override the equals method, since you define a duplicate condition based on quality hence in the equals method check for quality attribute value i.e.
public class Variant {
private String variant;
private String quantity;
public Variant(String variant, String quantity) {
this.variant = variant;
this.quantity = quantity;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((quantity == null) ? 0 : quantity.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
return true;
}
}
Create a method which basically checking whether your list contains the duplicate entries(Variant) or not and return true and false accordingly:
private static boolean isListContainsDuplicateEntries(
ArrayList variantList) {
final List setToReturn = new ArrayList();
for (Variant v : variantList) {
if (!setToReturn.contains(v)) {
setToReturn.add(v);
} else {
return true;
}
}
return false;
}
Now, test the functionality:
public static void main(String[] args) {
Variant variant1 = new Variant("1", "100");
Variant variant2 = new Variant("2", "200");
Variant variant3 = new Variant("3", "200");
ArrayList<Variant> variantList = new ArrayList<>();
variantList.add(variant1);
variantList.add(variant2);
variantList.add(variant3);
System.out.println(Variant.isListContainsDuplicateEntries(variantList));
Output: true
You can use contains():
if (variantList.contains(**<some other Variant object>**)){
...
}
You can simply override your equals method in your Variant and try like this
List<Varient> list =getVariantsList();
System.out.println("here list size"+list.size());
Set<Varient> set = new HashSet<Varient>(list);
System.out.println("here"+set.size());
Create a varient Object:
public class Varient {
private String variant;
private String quantity;
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Varient)) return false;
Varient varient = (Varient) o;
if (!quantity.equals(varient.quantity)) return false;
if (!variant.equals(varient.variant)) return false;
return true;
}
#Override
public int hashCode() {
int result = variant.hashCode();
result = 31 * result + quantity.hashCode();
return result;
}
}
Here is your main Program;
public class Test {
public static void main (String [] args){
// getVariantsList() here your list
List<Varient> list =getVariantsList();
Set<Varient> set = new LinkedHashSet<Varient>(list);
}
}
public class Variant {
private String variant;
private String quantity;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((variant == null) ? 0 : variant.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (variant == null) {
if (other.variant != null)
return false;
} else if (!variant.equals(other.variant))
return false;
return true;
}
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static void main(String[] args) {
// HashSet<Variant> set = new HashSet<>();
// LinkedHashSet<Variant> linkedSet = new LinkedHashSet<>(); // stores
// in input order
/*
* You can use treeset to store data in custom order, in this case
* lexicographically
*/
TreeSet<Variant> treeSet = new TreeSet<>(new VariantComparator());
}
}

In Collections, how can i get the index using the indexOf method in the following example

class Fruit{
public String name;
Fruit(String name){
this.name = name;
}
}//end of Fruit
class FruitList{
public static void main(String [] arg5){
List<Fruit> myFruitList = new ArrayList<Fruit>();
Fruit banana = new Fruit("Banana");
//I know how to get the index of this banana
System.out.println("banana's index "+myFruitList.indexOf(banana));
//But i'm not sure how can i get the indices for the following objects
myFruitList.add(new Fruit("peach"));
myFruitList.add(new Fruit("orange"));
myFruitList.add(new Fruit("grapes"));
}//end of main
}//end of FruitList
Since the rest of the objects that i've added to the ArrayList have no references, i'm not quite sure how their index can be retrieved. Please help, Thanks so much.
It does not matter which reference the object has if you redefine the equals and hashcode methods in the Fruit class. indexOf, contains, etc use the equals(...) method to decide if the object exists inside the collection.
For example, your Fruit class, could be like this (I changed your public String name to private):
public class Fruit {
private String name;
public Fruit(String name){
this.name = name;
}
public String getName() {
return name;
}
#Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Fruit other = (Fruit) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
Then:
Fruit f = new Fruit("orange");
myFruitList.indexOf(f); // this should return the orange fruit index (would be 1 in your example).

How to override equals() method

public class Car
{
private String name;
public int id;
public Car(String name, int id)
{
this.name = name;
this.id = id;
}
#Override
public boolean equals(Object ob)
{
if (!(ob instanceof Car))
{
return false;
}
Car that = (Car)ob;
return this.id == that.id;
}
#Override
public int hashCode()
{
return id;
}
// this class also got getters and setters
Then I got another class
public class CarList
{
private Collection<Car> cars;
public CarList()
{
cars = new HashSet<>();
}
public boolean insertCar(Car car)
{
return cars.add(car);
}
My question is: How to properly override equals() and hashCode() method, where I consider 'id' and 'name' attribute for object comparsion and hashCode calculation ( so there is no possibility to have 2 objects with the same name and ID - because in this code as it is - it only takes 'id' attribute for object comparsion)?
As of Java 7, there are static methods on Objects that makes implementing hashCode and equals easier. This should work well, assuming you don't want to use getClass() instead of instanceof to determine type compatibility. That depends on how subclasses of Car should compare to Cars.
#Override
public boolean equals(Object ob)
{
if (!(ob instanceof Car))
{
return false;
}
Car that = (Car)ob;
return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name);
}
#Override
public int hashCode()
{
return Objects.hash(id, name);
}
Instead of using
if (!(ob instanceof Car))
{
return false;
}
You should think about using
if (getClass() != obj.getClass())
return false;
Lets assume you have ForWdCar extends Car and TwoWdCar extends Car with equal name and id.
Do you want them to be equal? 1st solution,
Do you want them to be unequal? 2nd solution
You don't care, such cases don't happen? Second solution, it's faster.

How can I override equals() method using inheritance?

I have a subclass called "worker" extending the "Person" class. I am trying to override the equals() method from "Person" within the subclass of "Worker". Can anyone explain if my attempt is correct in terms of a basic override?
public class Person {
private String name;
public Person(String n) {
name = n;
}
public Person() {
this("");
}
public String getName() {
return name;
}
public String toString() {
return getName() + " ";
}
public boolean equals(Object rhs) {
if (!(rhs instanceof Person)) {
return false;
}
Person other = (Person) rhs;
return this.getName().equals(other.getName());
}
class Employee extends Person {
double salary;
public Employee(double b) {
salary = b;
}
Employee() {
salary = 150000;
}
public double getSalary() {
return salary;
}
#Override
public String toString() {
return super.toString();
}
// my attempt
#Override
public boolean equals(Object rhs) {
if (rhs == null) {
return false;
}
if (getClass() != rhs.getClass()) {
return false;
}
if (!super.equals(rhs))
return false;
else {
}
return false;
}
}
}
You've sort of mechanically handled the override part correctly, but the equals method of your Employee class will never return true.
First because of this:
if (!super.equals(rhs)) return false; else { }
You'll always fall through to the final return false, even if the result of super.equals is true.
Once you fix that, you still have a problem with the equals method of Person. If you pass in an instance of Worker, that equals method will always return false.
There may yet be other things, but those two are show stoppers.
The NetBeans using the shortcut alt + insert, you can automatically generate the equals method, constructors, getters, setters, delegate method, and others. If you want to use the collection using encoding mixing(Hashtable, HashMap, HashSet) it with redefining equals you must also redefine the hashCode().

Categories

Resources