How to compare objects from a same class based on their attributes? - java

I have this objects:
COSTOS Costos = new COSTOS(1781, 359.13, "BISAG.SUP.PUER.TRA.I", "67550T9AT00ZZ");
COSTOS Herramienta = new COSTOS(1795, 299.11, "BISAG.INF.PUER.TRA.I", "67960T2MT02ZZ");
And this is my class:
public class COSTOS implements Comparable<COSTOS>{
public int referencia;
public double monto;
public String descripcion;
public String NumeroParte;
//Constructor
//getters setters
Also, i implemented HashCode and equals:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((NumeroParte == null) ? 0 : NumeroParte.hashCode());
result = prime * result + ((descripcion == null) ? 0 : descripcion.hashCode());
long temp;
temp = Double.doubleToLongBits(monto);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + referencia;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
COSTOS other = (COSTOS) obj;
if (NumeroParte == null) {
if (other.NumeroParte != null)
return false;
} else if (!NumeroParte.equals(other.NumeroParte))
return false;
if (descripcion == null) {
if (other.descripcion != null)
return false;
} else if (!descripcion.equals(other.descripcion))
return false;
if (Double.doubleToLongBits(monto) != Double.doubleToLongBits(other.monto))
return false;
if (referencia != other.referencia)
return false;
return true;
}
How could i implement a method that could print all the attributes
that are not equals?
I tried to use "import java.util.Objects;" to use: "Objects.hash(referencia, monto, descripcion, NumeroParte);", so that may give me the results to print

First, your methods can be simplified by using the null-safe Objects helper methods added in Java 7:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(this.NumeroParte);
result = prime * result + Objects.hashCode(this.descripcion);
result = prime * result + Double.hashCode(this.monto);
result = prime * result + this.referencia;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
COSTOS other = (COSTOS) obj;
return (Objects.equals(this.NumeroParte, other.NumeroParte)
&& Objects.equals(this.descripcion, other.descripcion)
&& Double.doubleToLongBits(this.monto) == Double.doubleToLongBits(other.monto)
&& this.referencia == other.referencia);
}
How could i implement a method that could print all the attributes that are not equals?
To print differences, do the same comparisons as the equals method:
public void printDifferences(COSTOS other) {
if (! Objects.equals(this.NumeroParte, other.NumeroParte))
System.out.println("Different NumeroParte: " + this.NumeroParte + " != " + other.NumeroParte);
if (! Objects.equals(this.descripcion, other.descripcion))
System.out.println("Different descripcion: " + this.descripcion + " != " + other.descripcion);
if (Double.doubleToLongBits(this.monto) != Double.doubleToLongBits(other.monto))
System.out.println("Different monto: " + this.monto + " != " + other.monto);
if (this.referencia != other.referencia)
System.out.println("Different referencia: " + this.referencia + " != " + other.referencia);
}

If I understand you requirement correctly, you want to print out the values of attributes which are not the same in 2 objects, then you can create a method as follows.
public void compareAttributes(COSTOS other) {
if (this.getMonto() != other.getMonto()) {
System.out.println("Not equal. This obj : " + this.getMonto()
+ " Other obj : " + other.getMonto());
}
// you can do the same for the remaining attributes.
}
EDIT:
As #Andreas, pointed out in the comments you should place this method in your COSTOS class itself so every object can be compared easily.

Related

java set holds element equals to a search key, but return false for 'contains' method

How can it be that a set holds the key as a first element
but contains method returns false?
Does it means the element was different when inserted into the set?
public class RuleConditionBl {
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RuleConditionBl that = (RuleConditionBl) o;
if (weight != that.weight) return false;
if (isAll != that.isAll) return false;
if (countries != null ? !countries.equals(that.countries) : that.countries != null) return false;
if (userFlag != that.userFlag) return false;
return datesRange != null ? datesRange.equals(that.datesRange) : that.datesRange == null;
}
#Override
public int hashCode() {
// int result = weight;
int result = 0;
result = 31 * result + (isAll ? 1 : 0);
result = 31 * result + (countries != null ? countries.hashCode() : 0);
result = 31 * result + (userFlag != null ? userFlag.hashCode() : 0);
result = 31 * result + (datesRange != null ? datesRange.hashCode() : 0);
return result;
}

Hibernate ManyToMany mapping infinite DB calls

Award Entity
#JsonIgnore
#ManyToMany(mappedBy="awards", fetch=FetchType.LAZY)
private Set<Winner> winners = new HashSet<>();
Winner Entity
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="AWARD_ASSIGNMENT",
joinColumns={#JoinColumn(name="WINNER_ID", referencedColumnName="ID")},
inverseJoinColumns={#JoinColumn(name="AWARD_ID", referencedColumnName="ID")})
private Set<Award> awards = new HashSet<>();
I am calling this hibernate fetch method
return getSession().createQuery("from Winner").list();
Hashcode equals method overriding in Awards entity
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((winners == null) ? 0 : winners.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;
Award other = (Award) obj;
if (id != other.id)
return false;
if (winners == null) {
if (other.winners != null)
return false;
} else if (!winners.equals(other.winners))
return false;
return true;
}
Winner entity
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((awards == null) ? 0 : awards.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Winner other = (Winner) obj;
if (awards == null) {
if (other.awards != null)
return false;
} else if (!awards.equals(other.awards))
return false;
if (id != other.id)
return false;
return true;
}
Overriding equals and hashcode methods as Many to Many relation is using SET.
Points to remember :
1) Make sure there are not Associations(One to many/ Many to many ..etc) in your hashcode or equal methods. while overriding hashcode / equals method use fields which make that object unique (ex.. FirstName + LastName + Phone number) try to avoid using PK Id generated by JPA .
2) Restrict Jackson/Json serialisation to avoid deep traversal .
#JsonManagedReference
private Set<Award> awards = new HashSet<>();
#JsonBackReference
private Set<Winner> winners = new HashSet<>();

Java Why two this same List when I check if are equals I see false [duplicate]

This question already has answers here:
Why do I need to override the equals and hashCode methods in Java?
(31 answers)
Closed 6 years ago.
Hi I have Two lists of objects :
public class TimeTableForBus {
String bsName;
int bsType;
Time ttTime;
int lon;
int lat;
int ttID;
int bus_stop_status;
}
And I generated two list just like this :
private static ArrayList getList( QueryRunner qRunner, Connection conn){
try {
beans = (List) qRunner.query(conn, "call mpklocal.LCD_GetDispInfoAllTimeTable()",
new BeanListHandler(TimeTableForBus.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < beans.size(); i++) {
TimeTableForBus bean = (TimeTableForBus) beans.get(i);
// bean.print();
}
ArrayList<TimeTableForBus> bus = new ArrayList<>();
for (int i = 0; i < beans.size(); i++) {
bus.add((TimeTableForBus) beans.get(i));
}
return bus;
}
When I check if are equals I see false when I do this I see false . The list have this same objects:
public static boolean equalLists(List<TimeTableForBus> one, List<TimeTableForBus> two){
if (one == null && two == null){
return true;
}
if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}
//to avoid messing the order of the lists we will use a copy
//as noted in comments by A. R. S.
// one = new ArrayList<String>(one);
// two = new ArrayList<String>(two);
//
// Collections.sort(one);
// Collections.sort(two);
return one.equals(two);
}
public static boolean listsAreEquivelent(List<? extends Object> a, List<? extends Object> b) {
if(a==null) {
if(b==null) {
//Here 2 null lists are equivelent. You may want to change this.
return true;
} else {
return false;
}
}
if(b==null) {
return false;
}
Map<Object, Integer> tempMap = new HashMap<>();
for(Object element : a) {
Integer currentCount = tempMap.get(element);
if(currentCount == null) {
tempMap.put(element, 1);
} else {
tempMap.put(element, currentCount+1);
}
}
for(Object element : b) {
Integer currentCount = tempMap.get(element);
if(currentCount == null) {
return false;
} else {
tempMap.put(element, currentCount-1);
}
}
for(Integer count : tempMap.values()) {
if(count != 0) {
return false;
}
}
return true;
}
And I don't know why I have this result
Try to override public boolean equals(Object o) and public int hashCode() like this:
public class TimeTableForBus {
String bsName;
int bsType;
Time ttTime;
int lon;
int lat;
int ttID;
int bus_stop_status;
#Override
public int hashCode() {
int result = 31;
result = 37 * result + generateHash(bsName);
result = 37 * result + generateHash(bsType);
result = 37 * result + generateHash(ttTime);
result = 37 * result + generateHash(lon);
result = 37 * result + generateHash(lat);
result = 37 * result + generateHash(ttID);
result = 37 * result + generateHash(bus_stop_status);
return result;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof TimeTableForBus))
return false;
TimeTableForBus model = (TimeTableForBus)o;
return Objects.equals(bsName, model.bsName)
&& bsType == model.bsType
&& Objects.equals(ttTime, model.ttTime)
&& lon == model.lon
&& lat == model.lat
&& ttID == model.ttID
&& bus_stop_status == model.bus_stop_status;
}
private int generateHash(long value) {
return (int)(value ^ (value >>> 32));
}
private int generateHash(Object value) {
return value == null ? 0 : value.hashCode();
}
}

Java homework: using an equals method with an array of objects [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have created an array of Song objects. A song contains the variables title, author, interpreter, (int)yearReleased, album, and fileName. I am using a main method to test my array of songs and my equals method. The test is supposed to fill an array with five song objects and use my equals method to ensure the new entry is not a duplicate of a previous entry. My test class compiles, but when I enter duplicate song information I keep getting an error. If anyone could give me a tip or point me in the correct direction I would greatly appreciate it. Any other tips would also be great. As a student, it is great to hear good real world advice from professionals.
import java.util.Scanner;
public class Test{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
Song[] songTest = new Song[5];
boolean match;
int count = 0;
System.out.println("Enter 5 songs\n");
for(Song x:songTest)
{
do{
match = false;
x = new Song();
System.out.print("Title: ");
x.setTitle(kybd.nextLine());
System.out.print("Author: ");
x.setAuthor(kybd.nextLine());
System.out.print("Interpreter: ");
x.setInterpreter(kybd.nextLine());
System.out.print("Year released: ");
x.setYearReleased(kybd.nextInt());
kybd.nextLine();
System.out.print("Album: ");
x.setAlbum(kybd.nextLine());
System.out.print("File name: ");
x.setFileName(kybd.nextLine());
System.out.print(x);
System.out.println();
for(int i = 0; i<count; i++)
if(songTest[i].equals(x)){
match = true;
System.out.print("Duplicate");
}
}while(match);
count++;
}
}
}
public class Song
{
public String title;
public String author;
public String interpreter;
public int yearReleased;
public String album;
public String fileName;
//private vars
private int reviewScore = 0;
private int reviews = 0;
private double average;
//Mutator methods
public void setTitle(String t)
{
this.title = t;
}
public void setAuthor(String a)
{
this.author = a;
}
public void setInterpreter(String i)
{
this.interpreter = i;
}
public void setYearReleased(int y)
{
if (y>0)
this.yearReleased = y;
else
{
System.out.print ("This song is not that old");
this.yearReleased = -5;
}
}
public void setAlbum(String a)
{
this.album = a;
}
public void setFileName(String f)
{
this.fileName = f;
}
public void addReviewScore(int s)
{
if (s>0 && s<6)
{
this.reviewScore += s;
this.reviews++;
}
else
System.out.print("This is not a valid review score!");
}
//Accessor methods
public String getTitle()
{
return this.title;
}
public String getAuthor()
{
return this.author;
}
public String getInterpreter()
{
return this.interpreter;
}
public int getYearReleased()
{
return this.yearReleased;
}
public String getAlbum()
{
return this.album;
}
public String getFileName()
{
return this.fileName;
}
public double getAverage()
{
this.average = this.calculateAverage();
return this.average;
}
//Methods
public boolean equals(Song otherSong)
{
boolean isEqual = false;
//compare this song to the otherSong
isEqual =
this.title == otherSong.title &&
this.author == otherSong.author &&
this.interpreter == otherSong.interpreter &&
this.yearReleased == otherSong.yearReleased &&
this.album == otherSong.album &&
this.fileName == otherSong.fileName;
return isEqual;
}
public String toString()
{
String songInfo;
songInfo =
"***Song information***\n" +
"Title: " + this.title +
"\nAuthor: " + this.author +
"\nInterpreter: " + this.interpreter +
"\nYear Released: " + this.yearReleased +
"\nAlbum: " + this.album +
"\nFile name: " + this.fileName +
"\nYears old: " + this.yearsOld();
return songInfo;
}
public int yearsOld()
{
int yearsOld = (2012 - this.yearReleased);
return yearsOld;
}
//Private methods
private double calculateAverage()
{
this.average = ((double)this.reviewScore/(double)this.reviews);
return this.average;
}
}
I tried your code and reproduced the error which occurs at this line:
if(songTest[i].equals(x)){
rewriting your equals method (or getting eclipse to do it for me) and adding the hashCode() solved the problem:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((album == null) ? 0 : album.hashCode());
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(average);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result
+ ((fileName == null) ? 0 : fileName.hashCode());
result = prime * result
+ ((interpreter == null) ? 0 : interpreter.hashCode());
result = prime * result + reviewScore;
result = prime * result + reviews;
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + yearReleased;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Song other = (Song) obj;
if (album == null) {
if (other.album != null)
return false;
} else if (!album.equals(other.album))
return false;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (Double.doubleToLongBits(average) != Double
.doubleToLongBits(other.average))
return false;
if (fileName == null) {
if (other.fileName != null)
return false;
} else if (!fileName.equals(other.fileName))
return false;
if (interpreter == null) {
if (other.interpreter != null)
return false;
} else if (!interpreter.equals(other.interpreter))
return false;
if (reviewScore != other.reviewScore)
return false;
if (reviews != other.reviews)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (yearReleased != other.yearReleased)
return false;
return true;
}
you also seem to have a problem with the counter not incrementing properly, but I'm not going to do all of you homework for you! ;)
edit:
Woah!
You're also missing something like
songTest[i] = song;
to add the checked song to your array.
also, to make sure your first song gets put in I added:
if(i==0){
songTest[i] = x;
}
before your check.
The i is and int I added by changing your first for loop back to the old fashioned version, and I renamed your inner for loop to j.
Now it works.
try putting in something like:
System.out.println("i: " + i + " j: " + j + " count: " + count);
to see what's going on with your counters
You also exit after finding a duplicate. Is this the behavior you want? Or would it be better to notify the user, and continue inputting song data.
When I run this, I get a null pointer exception on this line
if(songTest[i].equals(x)){
It looks like you're not actually putting the song object (x) into the array.

How to say two java objects are equal with case ignore?

I have two java user defined java objects, how can i make these two objects to return same references with case ignore
Sample code:
public class compare{
private String name;
private Integer number;
}
java.lang.String has a method for this:
myString.equalsIgnoreCase("MyStRiNg");
If this is not what you are looking for please be more specific.
You must override hashcode and equals to properly compare two objects. The following is an IDE generated hashCode and equals method.
class A
{
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((number == null) ? 0 : number.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;
A other = (A) obj;
if (name == null)
{
if (other.name != null)
return false;
}
else if (!name.equalsIgnoreCase(other.name))
return false;
if (number == null)
{
if (other.number != null)
return false;
}
else if (!number.equals(other.number))
return false;
return true;
}
String name;
Integer number;
}

Categories