Java Reference
In-Depth Information
Casting is not needed to retrieve a value from a list with a specified element type, because
the compiler already knows the element type. For example, the following statements create a
list that contains strings, add strings to the list, and retrieve strings from the list.
no casting needed
1 ArrayList<String> list =
new
ArrayList<>();
2 list.add(
"Red"
);
3 list.add(
"White"
);
4 String s = list.get(
0
);
// No casting is needed
Prior to JDK 1.5, without using generics, you would have had to cast the return value to
String
as:
String s = (String)(list.get(
0
));
// Casting needed prior to JDK 1.5
If the elements are of wrapper types, such as
Integer
,
Double
, and
Character
, you can
directly assign an element to a primitive type variable. This is called
autounboxing
, as intro-
duced in Section 10.8. For example, see the following code:
autounboxing
1 ArrayList<Double> list =
new
ArrayList<>();
2 list.add(
5.5
);
// 5.5 is automatically converted to new Double(5.5)
3 list.add(
3.0
);
// 3.0 is automatically converted to new Double(3.0)
4 Double doubleObject = list.get(
0
);
// No casting is needed
5
double
d = list.get(
1
);
// Automatically converted to double
In lines 2 and 3,
5.5
and
3.0
are automatically converted into
Double
objects and added to
list
. In line 4, the first element in
list
is assigned to a
Double
variable. No casting is nec-
essary, because
list
is declared for
Double
objects. In line 5, the second element in
list
is
assigned to a
double
variable. The object in
list.get(1)
is automatically converted into
a primitive type value.
19.1
✓
✓
Are there any compile errors in (a) and (b)?
Check
Point
ArrayList dates =
new
ArrayList();
dates.add(
new
Date());
dates.add(
new
String());
ArrayList<Date> dates =
new
ArrayList<>();
dates.add(
new
Date());
dates.add(
new
String());
(a) Prior to JDK 1.5
(b) Since JDK 1.5
19.2
What is wrong in (a)? Is the code in (b) correct?
ArrayList dates =
new
ArrayList();
dates.add(
new
Date());
Date date = dates.get(
0
);
ArrayList<Date> dates =
new
ArrayList<>();
dates.add(
new
Date());
Date date = dates.get(
0
);
(a) Prior to JDK 1.5
(b) Since JDK 1.5
19.3
What are the benefits of using generic types?
A generic type can be defined for a class or interface. A concrete type must be
specified when using the class to create an object or using the class or interface to
declare a reference variable.
Key
Point
Search WWH ::
Custom Search