Compare Java Objects using equals method

You can compare 2 java objects using the equals method. The equals method is provided by the java super class “Object

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
public class EqualsMethod {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

animal zebra = new animal ( "Zebra" , "Herbivore");
animal giraffe = new animal ( "Giraffee" , "Herbivore");
animal ZEBRA = new animal ( "ZEBRA" , "HERBIVORE");

if (zebra.equals(ZEBRA))
{
System.out.println ( " Object zebra is same as ZEBRA ");
}

if ( zebra.equals(giraffe))
{
System.out.println ( " zebra is same as giraffe" );
}

}

}

class animal
{
String name ;
String type ;

animal ( String name , String type)
{
this.name = name;
this.type = type;
}

public boolean equals( animal a)
{
if ( this.name.equalsIgnoreCase(a.name) && this.type.equalsIgnoreCase(a.type))
{
return true;
}
else return false;
}
}
[/java]

 

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
public class car
{
String engine_cc ;
String engine_type;
String model;
String make;
}
[/java]

Question 1 : Write an equals method for the class car so that it returns a “true” if all the instance variables, engine_cc, engine_type, model and make are equal.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s