Example: Stack ADT
- elements are added and removed from the same end; LIFO (Last In First Out)
push() ==> Add (Push) an element
pop() ==> Remove (pop) an element
peek() ==> Look at the top element w/o removing it
is Empty()
size()
Assume some type T to be held by the stack
where T is just a placeholder
push(T elem)
T pop()
T peek ()
boolean is Empty()
Generic Types
Animal[] creatures = new Mammal[25];
.
..
...
creatures[1] = new Lizard () ;
This causes a runtime error because Lizard is not a subclass of Mammal.
Generic types allow us to help the compiler by providing additional hints about data types.
Recall the comparable interface
class Apple implements Comparable {
.
..
...
public int compareTo (Object otherObject)
.
..
...
}
Comparable is actually a generic interface :
public interface Comparable
public int compareTo ( T thing) ;
}
To compare Apples to Apples (only!)
class Apple implements Comparable
.
..
..
public int compareTo (Apple otherApple) {.....} ;
Text uses this language:
"Then, when a generic class is needed, it is instantiated with a specific class used in place of T."
Would be nice to allow:
class Apple implement Comparable
But doesnt work!
Subtly wrong - information about the actual type used for T is not part of the runtime hidden bookkeeping information. Generics are enforced by the compiler.
No comments:
Post a Comment