Java Reference
In-Depth Information
Chapter Summary
•
The main
collection
interfaces are
Collection<T>
,
Set<T>
, and
List<T>
. The
Set<T>
and
List<T>
interfaces extend the
Collection<T>
interface. The
library classes that are standard to use and that implement these interfaces are
HashSet<T>
, which implements the
Set<T>
interface, and
ArrayList<T>
, which
implements the
List<T>
interface.
•
A
Set<T>
does not allow repeated elements and does not order its elements.
A
List<T>
allows repeated elements and orders its elements.
•
The
Map<K,V>
interface is used to store a mapping between a key
K
and a value
V
.
It is commonly used to store databases in memory. The
HashMap<K,V>
class is a
standard library class that implements a map.
•
An
iterator
is something that allows you to examine and possibly modify the ele-
ments in a collection in some sequential order. Java formalizes this concept with
the two interfaces
Iterator<T>
and
ListIterator<T>
.
•
An
Iterator<T>
(with only the required methods implemented) goes through the
elements of the collection in one direction only, from the beginning to the end.
A
ListIterator<T>
can move through the collection list in both directions, for-
ward and back. A
ListIterator<T>
has a set method; the
Iterator<T>
interface
does not require a set method.
Answers to Self-Test Exercises
1 .
public static
<T>
boolean
inSome(T target,
Collection<T> c1, Collection<T> c2)
{
return
(c1.contains(target) || c2.contains(target));
}
2 .
public static
<T> T getFirst(List<T> aList)
{
if
(aList.isEmpty())
return null
;
else
return
aList.get(0);
}
3.
public static boolean
noNull(Set<?> s)
{
return
(s.remove(
null
));
}
4. No.