Java Generics
Java Generics is a new feature introduced in JDK 5. Generics provide a compile-time type-safety detection mechanism that allows programmers to detect illegal types at compile time.
The essence of generics is parameterized types, meaning the data type being operated on is specified as a parameter.
Suppose we have a requirement: write a sorting method that can sort integer arrays, string arrays, and even arrays of any other type. How can we implement this?
The answer is to use Java Generics.
Using the concept of Java generics, we can write a generic method to sort an array of objects. Then, call this generic method to sort integer arrays, floating-point arrays, string arrays, etc.
Generic method
You can write a generic method that can receive different types of parameters when called. Based on the parameter type passed to the generic method, the compiler appropriately handles each method call.
The following are the rules for defining generic methods:
- All generic method declarations have a type parameter declaration section (delimited by angle brackets), which appears before the method's return type (in the example below, it is
). - Each type parameter declaration section contains one or more type parameters, separated by commas. A generic parameter, also called a type variable, is an identifier used to specify a generic type name.
- Type parameters can be used to declare the return value type and serve as placeholders for the actual argument types obtained by the generic method.
- The declaration of a generic method body is the same as other methods. Note that a type parameter can only represent reference types, not primitive types (such as int, double, char etc.).
Generic type markers in Java:
- E - E — Element (used in collections, because collections store elements)
- T - T — Type (Java class)
- K - K — Key
- V - V — Value
- N - N — Number
- ? - ? — represents an uncertain Java type
Example
The example below demonstrates how to use a generic method to print elements of arrays of different types:
Example
public
class
GenericMethodTest
{
//
Generic method printArray
public
static
<
E
void
printArray
(
E
[
]
inputArray
)
{
//
Output array elements
for
(
E
element
:
inputArray
)
{
System
.
out
.
printf
(
"
%s
"
,
element
)
;
}
System
.
out
.
println
(
)
;
}
public
static
void
main
(
String
args
[
]
)
{
//
Create arrays of different types: Integer, Double, and Character
Integer
[
]
intArray
=
{
1
,
2
,
3
,
4
,
5
}
;
Double
[
]
doubleArray
=
{
1
.1
,
2
.2
,
3
.3
,
4
.4
}
;
Character
[
]
charArray
=
{
'
H
'
,
'
E
'
,
'
L
'
,
'
L
'
,
'
O
'
}
;
System
.
out
.
println
(
"
Integer array elements are:
"
)
;
printArray
(
intArray
)
;
//
Pass an integer array
System
.
out
.
println
(
"
\n
Double array elements are:
"
)
;
printArray
(
doubleArray
)
;
//
Pass a double array
System
.
out
.
println
(
"
\n
Character array elements are:
"
)
;
printArray
(
charArray
)
;
//
Pass a character array
}
}
Compile the above code; the run result is as follows:
Integer array elements are:
1 2 3 4 5
Double-precision array elements are:
1.1 2.2 3.3 4.4
Character array elements are:
H E L L O
Bounded type parameters:
Sometimes you may want to restrict the range of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers may only want to accept instances of Number or its subclasses. This is the purpose of bounded type parameters.
To declare a bounded type parameter, first list the type parameter name, followed by the extends keyword, and then immediately by its upper bound.
Example
The example below demonstrates how "extends" is used in the general sense meaning "extends" (class) or "implements" (interface). The generic method in this example returns the maximum of three comparable objects.
Example
public
class
MaximumTest
{
//
Compare three values and return the maximum
public
static
<
T
extends
Comparable
<
T
T
maximum
(
T
x
,
T
y
,
T
z
)
{
T
max
=
x
;
//
Assume x is the initial maximum
if
(
y
.
compareTo
(
max
)
0
)
{
max
=
y
;
//
y is larger
}
if
(
z
.
compareTo
(
max
)
0
)
{
max
=
z
;
//
Now z is larger
}
return
max
;
//
Return the maximum object
}
public
static
void
main
(
String
args
[
]
)
{
System
.
out
.
printf
(
"
The largest number among %d, %d, and %d is %d
\n
\n
"
,
3
,
4
,
5
,
maximum
(
3
,
4
,
5
)
)
;
System
.
out
.
printf
(
"
The largest number among %.1f, %.1f, and %.1f is %.1f
\n
\n
"
,
6
.6
,
8
.8
,
7
.7
,
maximum
(
6
.6
,
8
.8
,
7
.7
)
)
;
System
.
out
.
printf
(
"
The largest string among %s, %s, and %s is %s
\n
"
,
"
pear
"
,
"
apple
"
,
"
orange
"
,
maximum
(
"
pear
"
,
"
apple
"
,
"
orange
"
)
)
;
}
}
Compile the above code; the run result is as follows:
3, 4 和 5 中最大的数为 5
6.6, 8.8 和 7.7 中最大的数为 8.8
pear, apple 和 orange 中最大的数为 pear
Generic class
The declaration of a generic class is similar to that of a non-generic class, except that a type parameter declaration section is added after the class name.
Like generic methods, the type parameter declaration section of a generic class also contains one or more type parameters, separated by commas. A generic parameter, also called a type variable, is an identifier used to specify a generic type name. Because they accept one or more parameters, these classes are called parameterized classes or parameterized types.
Example
The following example demonstrates how we define a generic class:
Example
public
class
Box
<
T
{
private
T
t
;
public
void
add
(
T
t
)
{
this
.
t
=
t
;
}
public
T
get
(
)
{
return
t
;
}
public
static
void
main
(
String
[
]
args
)
{
Box
<
Integer
integerBox
=
new
Box
<
Integer
(
)
;
Box
<
String
stringBox
=
new
Box
<
String
(
)
;
integerBox
.
add
(
new
Integer
(
10
)
)
;
stringBox
.
add
(
new
String
(
"
Runoob Tutorial
"
)
)
;
System
.
out
.
printf
(
"
Integer value is: %d
\n
\n
"
,
integerBox
.
get
(
)
)
;
System
.
out
.
printf
(
"
String is: %s
\n
"
,
stringBox
.
get
(
)
)
;
}
}
Compile the above code; the run result is as follows:
整型值为 :10
字符串为 :Runoob Tutorial
Type wildcards
1. A type wildcard generally uses ? in place of a concrete type parameter. For example List> is logically the parent type of List
import java . util .*; public class GenericTest { public static void main ( String [ ] args ) { List < String name = new ArrayList < String ( ) ; List < Integer age = new ArrayList < Integer ( ) ; List < Number number = new ArrayList < Number ( ) ; name . add ( " icon " ) ; age . add ( 18 ) ; number . add ( 314 ) ; getData ( name ) ; getData ( age ) ; getData ( number ) ; } public static void getData ( List data ) { System . out . println ( " data : " data . get ( 0 ) ) ; } } The output is: Analysis: Because getData() the parameter of the method is List> type, so name, age, number can all be used as actual arguments for this method; this is the role of the wildcard. 2. The upper bound of a type wildcard is defined in the form List extends Number>, meaning the wildcard generic value accepts Number and its subtypes. import java . util .*; public class GenericTest { public static void main ( String [ ] args ) { List < String name = new ArrayList < String ( ) ; List < Integer age = new ArrayList < Integer ( ) ; List < Number number = new ArrayList < Number ( ) ; name . add ( " icon " ) ; age . add ( 18 ) ; number . add ( 314 ) ; // getUperNumber(name);//1 getUperNumber ( age ) ; // 2 getUperNumber ( number ) ; // 3 } public static void getData ( List data ) { System . out . println ( " data : " data . get ( 0 ) ) ; } public static void getUperNumber ( ListExample
data :icon
data :18
data :314
Example