Download presentation
Presentation is loading. Please wait.
Published byWarren Houston Modified over 9 years ago
1
Typecasting References Computer Science 3 Gerb Reference: Objective: Understand how to use the Object class in Java in the context of ArrayLists.
2
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.
3
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;
4
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;
5
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;
6
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.
7
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.