Java simple bugs Show key = new Show( \"Short Circuit\", 1986 ); Show someShow =
ID: 3898080 • Letter: J
Question
Java simple bugs
Show key = new Show( "Short Circuit", 1986 );
Show someShow = new Show( "Short Circuit", 1986 );
if(key == someShow){
System.out.println(key + " " + someShow + " are the same");
System.out.println();
}
else if (key != someShow){
System.out.println(key + " " + someShow + " are not the same");
System.out.println();
}
for some reason the key and some show are not equal i am not sure what do i write wrong, even though they are the same.
the show constructor only have 2 parameter
public Show(String title, int year)
{
this.title = new String( title );
this.year = year;
}
Explanation / Answer
if(key == someShow) by doing comparision like this wrong. Here the rquirement is you need to compare the equality of objects based on the variables equality but here you are comparing object references rather than each individual members. Change the condition in if as if(key.getTitle().equals(someShow.getTitle))&&key.getYear==someShow.getYear()) if you have getters in your show class.
This is known as deep comparision. But what you are doing is shallow comparision which will return true if both the objects pointing to same reference in memory.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.