





















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






















-^
LinkedList,
HashSet,
HashMap
Integer,
String
-^
-^
-^
^
Generics in Java provide away to communicate T, thetype of elements in acollection, to the compiler
Map
grades
new
HashMap();
grades.put("John",
new
Integer(67));
grades.put("Jane",
new
Integer(88));
grades.put("Fred",
new
Integer(72));
Integer
x
(Integer)grades.get("John");
sum
sum
x.intValue();
Map<String,
Integer> grades
new
HashMap<String,
Integer>();
grades.put("John",
new
Integer(67));
grades.put("Jane",
new
Integer(88));
grades.put("Fred",
new
Integer(72));
Integer
x^
grades.get("John");
sum
sum
x.intValue();
Map<String,
Integer> grades
new
HashMap<String,
Integer>();
grades.put("John",
new
Integer(67));
grades.put("Jane",
new
Integer(88));
grades.put("Fred",
new
Integer(72));
Integer
x
grades.get("John");
sum
sum
x.intValue();
This
is
true
wherever
c
is
used
The
compiler
checks
this
and
won’t
compile
code
that
violates
this
A
cast
tells
us
something
the
programmer
thinks
is
true
at
a
single
point
in
the
code
The
Java
virtual
machine
checks
whether
the
programmer
is
right
only
at
runtime
Programming
with
Generic
Types
-^
To
use
the
interface
List
,^ supply
an
actual
type
argument,
e.g.,
List
-^
All
occurrences
of
the
formal
type
parameter
(
E
in
this
case)
are
replaced
by
the
actual
type
argument
(
Integer
in
this
case)
public
interface
List
is
a
type
variable
void
add(E
x);
Iterator
iterator();
} public
interface
Iterator
next(); boolean
hasNext();
void
remove();
void
printCollection(Collection
c)
Iterator
i
c.iterator();
while
(i.hasNext())
System.out.println(i.next()); } } void
printCollection(Collection
c)
for
(Object
e^
c)
System.out.println(e); } }
void
printCollection(Collection<?>
c)
for
(Object
e
c)
System.out.println(e); } }
static
void
a2c(Object[] a,
Collection<?>
c)
for
(Object
o
a)
c.add(o);
compile
time
error
} public
class
myClass
static
void
a2c(T[]
a,
Collection
c)
for
o
a)
c.add(o);
ok
public class Queue
extends
AbstractBag
private java.util.LinkedList
= new
java.util.LinkedList
public void insert(T item) {
queue.add(item); } public T extract()
throws java.util.NoSuchElementException {
return queue.remove(); } public void clear() {
queue.clear(); } public int size() {
return queue.size(); } }
HashSet
TreeSet
ArrayList
LinkedList
HashMap
TreeMap
java.util.Iterator
(an
interface)
public boolean hasNext();^
public E next();^
public void remove();^
Additional
Methods
of
Collection
public Object[] toArray()^
public
Bulk
Operations: