Best and good way to do this is, override the equals()
method in Object
class:
public boolean equals(Object c){
if (c == null)
return false;
if (!CellAtt.class.isAssignableFrom(c.getClass()))
return false;
CellAtt obj = (CellAtt) c;
return this.brand.equals(obj.brand) && this.price == obj.price;
}
read this to understand how to override equals() in Object class?
If you strictly want to implement a method by yourself do this:
Modify the compare()
in CellAtt
class.
public boolean compare(CellAtt c){
if (c == null)
return false;
return this.brand.equals(c.brand) && this.price == c.price;
}
Then in the Main
class, you can invoke the method like below:
boolean res = c1.compare(c2);
System.out.println(res);//this is added to check output
UPDATE
Comlete code:
CellAtt
class:
public class CellAtt {
private String brand;
private long serial;
private double price;
public CellAtt(String brand, long serial, double price) {
this.brand = brand;
this.serial = serial;
this.price = price;
}
@Override
public boolean equals(Object c){
if (c == null)
return false;
if (!CellAtt.class.isAssignableFrom(c.getClass()))
return false;
CellAtt obj = (CellAtt) c;
return this.brand.equals(obj.brand) && this.price == obj.price;
}
//public boolean compare(CellAtt c){
// if (c == null)
// return false;
//
// return this.brand.equals(c.brand) && this.price == c.price;
//}
}
Main
class:
public class Main {
public static void main(String[] args) {
CellAtt c1 = new CellAtt("nokia",4536895,3600.00);
CellAtt c2 = new CellAtt("samsung",4536895,3600.00);
boolean res = c1.equals(c2);
// boolean res = c1.compare(c2);
System.out.println(res);
}
}