Java Reference
In-Depth Information
System.out.println(mySet);
mySet.remove("B");
System.out.println(mySet);
mySet.add("D");
System.out.println(mySet);
}
}
Clearly, using Java collections is much more straightforward. Notice again the
import
statement at
the top, before the class definition. Contrary to classes located in
java.lang
, you need to specify
which classes to use in your code when they are outside your current package. You will read about
packages and importing classes in Chapter 8, and Eclipse will help you to figure out which
import
statement to include, but the basic idea should be clear from this example.
So which data structures does Java provide out of the box? These are:
➤
Lists (classes implementing
java.util.List
), such as
ArrayList
and
LinkedList
, that
provide a user‐friendly alternative to arrays.
➤
Stacks (classes implementing
java.util.Stack
) that keep a stack of objects. A stack is a
last‐in‐first‐out (LIFO) data structure that allows you to add (push) new objects on top of the
stack and retrieve (pop) objects back out from the stack. As a metaphor, you can compare a
stack to a pile of papers on your desk. New papers (objects) are placed on top of the pile, and
every paper (object) can be taken from the top of the pile as well.
➤
Queues (classes implementing
java.util.Queue
) provide a data structure similar to a stack,
but with the difference that objects are taken from the beginning of the queue (first‐in‐first‐
out, FIFO). Double‐ended queues (
java.util.Dequeue
) are also provided and allow you to
insert and remove objects both at the front and the back.
➤
Sets (classes implementing
java.util.Set
), such as the
HashSet
and
TreeSet
, store a set of
objects (that is, a group of objects without duplicates).
➤
Maps (classes implementing
java.util.Map
) provide a simple data structure that associates
values (objects) with a key. That is, it
maps
keys to values. Think of a map as a dictionary (in
other programming languages, this is the term used for this data structure): the word being
looked up is the key, whereas the description is the value. Just as a real‐life dictionary orga-
nizes words according to the alphabet, maps in Java organize their keys in an efficient man-
ner, so retrieving values is generally very fast.
Maps, lists, and sets are by far the most commonly used collection types in Java. The following Try
It Out shows how they work.
Collections in Java
try it out
This Try It Out shows how collection types work in Java.
1.
Create a class called
CollectionsTester
in Eclipse.
2.
Add a
main
method. Create an
ArrayList
,
HashSet
, and
HashMap
variable and store some items,
so that the class looks like this:
Search WWH ::
Custom Search