Java Reference
In-Depth Information
The methods demonstrated here are in the
List
interface and therefore are available to
all
List
objects. Each implementation class of
List
also adds additional behaviors relevant
to the type of list. For example:
The
LinkedList
class implements a doubly linked list and contains the methods
addFirst
,
addLast
,
removeFirst
, and
removeLast
for adding and removing elements at
the beginning or end of the linked list.
The
Stack
class contains the methods
push
and
pop
for pushing and popping elements
onto the stack, as demonstrated in the sidebar “The Stack Class.”
The
Vector
class contains methods for array-like behaviors, like
elementAt
,
insertElementAt
, and
removeElementAt
.
The
ArrayList
class is a simple (but useful) implementation of the
List
interface and
basically contains the same methods as the
List
interface.
The
Stack
Class
The
Stack
class in
java.util
implements a
Stack
data structure as a list. The
Stack
class
defi nes a
push
method that pushes an item on the stack and a
pop
method that removes the
top object from the stack. For example, the following statements create a
Stack
for storing
Integer
objects and push two elements onto the stack:
Stack<Integer> mystack = new Stack<Integer>();
mystack.push(new Integer(100));
mystack.push(200);
Due to generics, only
Integer
types can be pushed on the
Stack
mystack
. (Pushing
200
is allowed because of Java's autoboxing feature.) The following line of code does not
compile:
mystack.push(“Not an Integer”);
The compiler error looks like
ListDemo.java:9: push(java.lang.Integer) in
java.util.Stack<java.lang.Integer> cannot be applied to
(java.lang.String)
mystack.push(“Not an Integer”);
^
The
pop
method of stack removes the top element and returns a reference to it. For
example:
Integer top = mystack.pop();
for(Integer i : mystack) {
System.out.println(i);
}
Search WWH ::
Custom Search