Showing posts with label Equality. Show all posts
Showing posts with label Equality. Show all posts

Friday, December 21, 2012

Consider if 2 objects are equal....

Demo Code Project: OverridingEquals.zip

Let's say you have the need to ensure that no 2 objects have the same contents - you want to check if one object is equal to another?

What do you consider equal?

Read on...

equals(Object)
The default implementation of the equals method, provided in all java objects (java.lang.Object) is to compare the memory location of one object, with another.


Consider the example above.

Two objects of type Asteroid1 have been instantiated using identical parameters - both a1 and a2 objects have the same contents. They do not, however, have the same memory location.

When the new operator is used, it causes the system to allocate memory space for the data and as such, a1 and a2 objects have unique memory locations.

When the equals method is used to compare the equality of these 2 objects, the equals method will return false - because each object has a different memory location.

If, for the purposes of your program, you consider that object equality is based on memory location only, the default implementation of the equals method is sufficient.

If however, you consider that object equality is based on the contents of objects themselves (more likely), read on...

overriding equals(Object)

All java objects (java.lang.Object) contain a default implementation of an equals method which compares the memory location of objects to determine equality. When writing your own libraries, you may find that this version of the method is not fit for your purpose. In this case, you can override the method and implement your own version of what you consider to be equality. It is usually the case that object equality relies on comparing the contents of the objects - not the memory locations.

When a class overrides a method, it is providing it's own version of a method that has already been provided by it's parent class (such as java.lang.Object).

You can override the equals method simply by providing your own, in your class. A couple of things to remember though:

The method signature must be the same as the one provided by java.lang.Object:

  • Public
  • Boolean return type
  • method name must be equals
  • takes a single parameter of Object type

...which looks like...



OK, now for the implementation. Our goal is to compare the contents of the object parameter with the contents of the current object.

Here is the definition of the class called Asteroid2:



Note that the equals method has been included in the method list.

The contents of this class are the values for the name, size and rotationRate fields. In our implementation of equals, we will write code which considers equality based upon the values of these fields.

Basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, we will consider the current object and the parameter object to be equal.

Here's the code:






The first line ensures that the parameter object (aThat) being passed to the method is of the correct type - in this case Asteroid2. The instanceof operator (compares an object to a specified type) is used to determine the type. The method returns false immediately if this is not found to be true - after all, if the parameter object isn't of type Asteroid2 then it will never be equal to any instance of Asteroid2.

The second line then goes ahead and casts (converts) the parameter object to the type it is being compared to - in this case, Asteroid2. Once the cast has taken place, we can then treat the parameter object (aThat) as an instance of Asteroid2 (That) and call each of it's methods to begin determining equality.

The return statement uses the logical operator && to join together a number of expressions, relating to the fields on the objects, which will ultimately evaluate to true or false.

Once again...basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, the method will return true.

Calling the equals method
Let's assume that we wish to add a new Asteroid2 object to an existing ArrayList of Asteroid2 objects but we want to make sure that an object with the same contents does not already exist in the ArrayList.

The example below uses a loop to compare the new Asteroid2 object with each object in the ArrayList:


Because the Asteroid2 class has overriden equals, we can be assured that only objects containing unique contents will be added to the ArrayList.

Incidentally, the ArrayList has a contains method which evaluates object equality in the same way - dispensing with the need for a loop. It simply calls the equals method on each object in the ArrayList - equality is based on whether the method has been overriden by the class in question (contents) or not (memory location).

One last thing...

We can also quickly return from the equals method by checking if the parameter object has the same memory location (and hence is the *same* object) as the current object.


When the equal to operator (==) is used on objects (reference types), the references (memory locations) are compared.

see also:

"Object (Java Platform SE 7 )" ( http://bit.ly/YrEmpk )

"Overriding and Hiding Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)" ( http://bit.ly/Zn8eop )


Wednesday, September 5, 2012

Comparing int using the equality operator


Two int values may be compared for equality by using the equals = = operator.

The equals operator returns True or False (boolean).


int one = "10";
int two = "10";

if (one == two) {
System.out.println("The int values are equal.");
}
else {

System.out.println("The int values are NOT equal.");
}


In this example, the equals operator would return true, causing the statement "The int values are equal" to be printed to screen.

The equals operator is used to test equality on all primitive types such as int.

If you need to compare two strings, read here....

Comparing String using the .equals method


Two String objects may be compared for equality by using the .equals function.

The equals method returns True or False (boolean).


String one = "Apples";
String two = "Oranges";

if (one.equals(two)) {
System.out.println("The strings match.");
}
else {

System.out.println("The strings DO NOT match.");
}



In this example, the equals method would return false, causing the statement "The strings DO NOT match" to be printed to screen.

The .equals function is available in all objects and Strings.

If you need to compare two primitive types such as int, read here....


Tuesday, August 7, 2012

equals


"Java: ==, .equals(), compareTo(), and compare()" ( http://bit.ly/Nygeae )

"Java Practices -> Implementing equals" ( http://bit.ly/MZN7Tb )

"Object equality - JavaWorld" ( http://bit.ly/MZNpJC )

Tuesday, May 8, 2012

ArrayList

An ArrayList is a resizable array. There is no need to tell the ArrayList how many items it can store.

Similar to an array, in that all objects in the ArrayList occupy an index (and remember, indexes begin at 0).

Additionally, items may be added and removed without providing an index.

Instantiating ArrayList

Syntax:
ArrayList<Type> identifier = new ArrayList<Type>();


example:
ArrayList<String> customerNames = new ArrayList<String>();


In the example above, the ArrayList can store a collection of Strings.

We can also add user defined types (Types/classes we have created) to ArrayList.

Let's say for instance we have a class type called Player. We can create an ArrayList to store a collection of Player objects:


example:
ArrayList<Player> playerList = new ArrayList<Player>();



Adding to ArrayList

Syntax:
identifier.add(object);


example:
playerList.add(new Player("baz",100));


In the example above, a Player is added to the ArrayList. The new object is added to the end of the list.

Notice that we can instantiate the Player object directly into the add method.

Alternatively, we could add an existing Player object to the ArrayList:

Player p = new Player("maz",200);
playerList.add(p);

Replacing an element in ArrayList

Syntax:
identifier.set(index,object);

example:
playerList.set(10, new Player("baz",100));


In the example above, a Player object at index 10 is replaced in the ArrayList.


Removing from ArrayList

Syntax:
identifier.remove(index);


example:
playerList.remove(3);


Check ArrayList for element

Syntax:
identifier.contains(object);

example:
playerList.contains(myObj);

In the example above, the list will return true or false depending on whether the object called obj is found in the list - note: you must override the equals method to use this effectively!.




Getting the number of items in ArrayList

Syntax:
identifier.size();


example:
playerList.size();



In the example below, the size function is used to set the continuation condition in a for loop:

for (int x = 0; x < playerList.size(); x ++) { }



Looping through ArrayList

ArrayList contains a method called get which enables you to return the object in the list at a specific index.

Syntax:
identifier.get(index);


example:
playerList.get(1);


In the above example, we get the Player object at index 1 (the second object in the list).

In the example below, we loop through an ArrayList, using the loop counter to get each object in turn:

for (int x = 0; x < playerList.size(); x ++) {
Player currentPlayer = playerList.get(x);
}

If there are 20 Player objects in the list, the loop will iterate 20 times. On each pass of the loop, the get method returns the Player object at the specified index. As we are using the loop counter to provide this value, we are able to get each object in the list, in turn.


Searching ArrayList for a particular object

In the following example, we search ArrayList for a Player object, by playerID (the particular playerID is passed to the function as a parameter). An equality comparison is performed within the loop using the equality operator ( = = ):

public Player searchForPlayer(int playerID) {
Player p = null;

for (int x = 0; x < playerList.size(); x ++) {
Player currentPlayer = playerList.get(x);
if (currentPlayer.getID == playerID) {
p = currentPlayer;
}
}
return p;
}

In the following example, we search ArrayList for a Player object, by playerName (the particular playerName is passed to the function as a parameter). An equality comparison is performed within the loops using the equals function:


public Player searchForPlayer(String playerName) {
Player p = null;

for (int x = 0; x < playerList.size(); x ++) {
Player currentPlayer = playerList.get(x);
if (currentPlayer.getName.equals(playerName) {
p = currentPlayer;
}
}
return p;
}

"ArrayList (Java 2 Platform SE v1.4.2)" ( http://bit.ly/Ja6HGS )