Type Casting
Download
Report
Transcript Type Casting
Typecasting References
Computer Science 3
Gerb
Reference:
Objective: Understand how to use the Object
class in Java in the context of ArrayLists.
Extracting Objects from
Arraylists
• Recall that the remove and get operations
on ArrayLists return an Object
• You must cast into the class you expect it to
be:
String s= (String) myList.get(0);
• Why? Three rules apply to determining
when casting is required for converting
from one class to another.
Rule#1: Casting is required when
converting an instance of a
superclass (like Object) into one of
its subclasses
• Could go wrong if the superclass instance isn’t
an instance of the subclass.
• E.g. not all Objects are strings
• E.g. If casting a Flower to a Rose, what if the
flower is not a Rose, but a Daisy?
• The cast tells java to check if it’s ok
Rose myRose = (Rose) flower;
Rule#2: Casting is not required when
converting instance of a subclass into
one of its superclasses
• Could not go wrong.
• E.g. If casting a Rose to a Flower, well all Roses
are Flowers
Flower myFlower = myRose;
Rule#3: Casting is impossible from
one object to another if neither is a
subclass or superclass of the other.
• Impossible.
• Can’t use casting to turn a Rose into a Daisy
• Gives a compiler error when possible, and an
exception all the time
Rose myRose = myDaisy;
Therefore...
• Must keep track of what types you store:
ArrayList myList = new ArrayList();
Integer myInt = new Integer(5);
myList.add(myInt); Adds Integer wrapper
myList.add(“A string”); Adds a string
String s= (String) myList.get(0);
• No compiler error, since String is an object
• But will crash with a type conversion error, because get
will return an Integer, which can’t be cast into a String.
Summary
• Java provides the ArrayList class to implement the
List interface
– Array implementation
– Define an interface by listing its methods
• Things to keep in mind when using Array Lists
– Stores objects.
– Primitive types are not objects.
– Must keep track of what type of object ArrayList
operations will return or risk a type conversion error.