Showing posts with label Comparison. Show all posts
Showing posts with label Comparison. Show all posts

Sunday, September 16, 2012

Casting


DOWNLOAD CODE PROJECT: Casting

Casting can be used to convert an object of one class type to another, within an inheritance hierarchy.

For instance, all Java objects inherit from the Object class. A class called Player may be implicitly cast into the type Object, as below:

Object o = New Player();

However, the following statement will not compile:

Player P = o;

This is because a Player object is always an instance of Object whereas an Object is not always an instance of Player (An Object is alllll kinds of things).

We need to tell the compiler that o is an instance of Player, as below:

Player P = (Player) o;

This is called explicit casting - or down casting. Note that the type we are casting to is included in the parentheses.

The Animal family
Consider a family of classes where Animal is the superclass and it has sub classes of Mammal and Fish. In this scenario, Animal is the generalisation and Mammal & Fish are the specialisation.



We could, for instance, create an ArrayList to store all types of Animal, as below:

ArrayList<Animal> animalList = new ArrayList<Animal>();

and to that list we could add any type of animal:

animalList.add(New Mammal());
animalList.add(New Fish());

When the Mammal & Fish object types are added to the ArrayList, they have been implicitly cast as Animal. This means that they may only be used in the context of Animal - only state and behaviour belonging to Animal will be accessible from theses objects (even though we can see their actual type, on the screen in front of us).

If we wish to use these objects as their specialised type, we must first discover their run time instance type and then use explicit casting - down casting, to convert.

Consider the following inheritance hierarchy:



(NOTE: The diagram shows the hierarchy incorrectly - Mammal and Fish should be swapped :P)

There are now 7 types of Animal and we have instantiated each type into the ArrayList, as below:

ArrayList<Animal> animalList = new ArrayList<Animal>();
animalList.add(New Animal());
animalList.add(New Mammal());
animalList.add(New Fish());
animalList.add(New Bass());
animalList.add(New Snapper());
animalList.add(New Wombat());
animalList.add(New Kangaroo());


Let's say we want to search the list for certain types of Animal - remember, currently the compiler sees them all as the generalised type - Animal, because that is the type of the ArrayList. 

We could look for specific types, such as Bass. Or we could look for types of specialised type - for instance, finding all types of Fish.

Getting the specific type - equals
In the example below, a loop is used to traverse the list of Animal, looking for objects of the specialised type Bass. 

The equals() comparison method is used on each object to evaluate whether it's run time class is equal to Bass.


Note the statement:


The getClass() method returns the run time class of the object. The equals() method then compares that type to the type mentioned in the parentheses. In this case, Bass.

In the next statement, if the evaluation is true (if the currentAnimal object was found to be of type Bass), the Animal object (currentAnimal) is explicitly cast to an object of type Bass (bass).



The bass object now has the context of Bass, meaning that it may access all state & behaviour of Bass, as well as Fish, as well as Animal.

Getting types of specialised type: instanceof operator
In the example below, a loop is used to traverse the list of Animal, looking for any objects which are types of Fish. Remember, Fish, as well as being a subclass of Animal, is also a superclass of Bass and Snapper.

The instanceof operator is used on each object to evaluate whether it's run time instance type is equal to Fish.



Note the statement:


The instanceof operator determines if the currentAnimal object is an instance of Fish, regardless of whether it's specific type if Bass or Snapper. This means that all objects of type Fish, Bass and Snapper will be discovered using this method.

In the next statement, if the evaluation is true (if the currentAnimal object was found to be an instance of Fish), the Animal object (currentAnimal) is explicitly cast to an object of type Fish (f).



The f object now has the context of Fish, meaning that it may access all state & behaviour of Fish, as well as Animal.


Wednesday, September 5, 2012

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, 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 )