Many reference types (e.g., classes and interfaces) are defined in terms of other types (for example, the type of their field, or the return or parameter
types of their methods). Generic types allow programmers to replace references to specific types, such
as String
, with references to a placeholder, or parameter type. The generic type can then be parameterized with different specific types. As illustrated in this code sample,
generic types allow for stronger compile-time type checking and more compact code through the elimination of casts.
/**
* Copyright (C) 2024 by Martin Robillard.
* See https://codesample.info/about.html
*/
package essentials;
import java.util.Iterator;
import java.util.List;
/**
* Represents a pair of objects of the same reference type.
*
* @param <T> The type of both objects of this pair.
*/
class Pair implements
{
private final T aFirst;
private final T aSecond;
public Pair(T pFirst, T pSecond)
{
aFirst = pFirst;
aSecond = pSecond;
}
public T first() { return aFirst; }
public T second() { return aSecond; }
public asStrings()
{
return new Pair(aFirst.toString(), aSecond.toString());
}
@Override
public iterator()
{
return List.of(aFirst, aSecond).iterator();
}
}
public class Generics
{
@SuppressWarnings({ "unused", "unchecked", "rawtypes" })
public static void main(String[] args)
{
// Parameterized Pair
pairOfIntegers = ();
int sum = pairOfIntegers.first() + pairOfIntegers.second();
for( Integer integer : pairOfIntegers )
{
System.out.println(integer);
}
String firstAsString = pairOfIntegers.asStrings().first();
// Pair
Pair rawPair = new Pair();
Integer element1 = (Integer) rawPair.first();
String element1AsString = rawPair.asStrings().first();
}
}
A generic type type is a type with at least one type parameter, placed in angle brackets directly after the type name. To be used, a generic type must be by supplying it with a type argument.
A generic type type is a type with at least one type parameter, placed in angle brackets directly after the type name. To be used, a generic type must be by supplying it with a type argument.
A generic type invocation consists of replacing the type parameter of a generic type with a type argument. For example,
invoking the generic type Pair<T>
with the type argument String
results in the parameterized type Pair<String>
.
A generic type invocation consists of replacing the type parameter of a generic type with a type argument. For example,
invoking the generic type Pair<T>
with the type argument String
results in the parameterized type Pair<String>
.
Here the generic type Pair
is both invoked and instantiated. The invocation
with the diamond operator results in type Pair<Integer>
. The instantiation
results in an object of type Pair
.
Here the generic type Pair
is both invoked and instantiated. The invocation
with the diamond operator results in type Pair<Integer>
. The instantiation
results in an object of type Pair
.
The arguments to the constructor of Pair
must be of type Integer
. Here the int
literal values
are autoboxed into instances of Integer
. The constructor call is the equivalent of
new Pair<>(Integer.valueOf(1), Integer.valueOf(2));
The arguments to the constructor of Pair
must be of type Integer
. Here the int
literal values
are autoboxed into instances of Integer
. The constructor call is the equivalent of
new Pair<>(Integer.valueOf(1), Integer.valueOf(2));
"A raw type is the name of a generic class or interface without any type arguments." In a raw type,
references to type parameters are replaced with reference to Object
. Raw types should not be
used.
The return values of first()
and second()
are auto-unboxed from Integer
to int
.
The return values of first()
and second()
are auto-unboxed from Integer
to int
.
Because the parameterized type PairIterable<Integer>
, it
is possible to use the foreach loop to iterate over it.
Use of a raw type allows to construct a Pair
object with elements of two different types,
which can be prevented by the compiler if the type is parameterized.
Use of a raw type allows to construct a Pair
object with elements of two different types,
which can be prevented by the compiler if the type is parameterized.
Because methods now return Object
, it is necessary to use a casting operator to
assign the result to a variable of a more specific type.
Because methods now return Object
, it is necessary to use a casting operator to
assign the result to a variable of a more specific type.
Comma-separated identifiers within angle brackets immediately following the type name are the type parameters valid for the scope of the type declaration.
By convention, "type parameters names are single, uppercase letters."
Within the body of a generic type, the name of a type parameter can be used as any other type name. When the type is invoked, the mentions are replaced by the type argument in the invocation.
Within the body of a generic type, the name of a type parameter can be used as any other type name. When the type is invoked, the mentions are replaced by the type argument in the invocation.
The diamond operator consists of two matching angle brackets. In effect it is an "empty" type invocation. It
indicates that the compiler should infer the type argument to invoke the generic type with. Here, the compiler
can infer the type argument String
from the return value of toString()
.
The diamond operator consists of two matching angle brackets. In effect it is an "empty" type invocation. It
indicates that the compiler should infer the type argument to invoke the generic type with. Here, the compiler
can infer the type argument String
from the return value of toString()
.
This code is a directive to the compiler not to warn about specific types of problems it finds in the code.
This code is a directive to the compiler not to warn about specific types of problems it finds in the code.
This implements
clause refers to a parameterized type Iterable<T>
. In this case, the type parameter T
of Pair<T>
becomes
the type argument for Iterable
. The consequence is that when a specific type (e.g., String
) is used to parameterize Pair
,
that same type value propagates to the type parameter of Iterable
.
for
statement (sometimes called the "for-each loop" statement).
This implements
clause refers to a parameterized type Iterable<T>
. In this case, the type parameter T
of Pair<T>
becomes
the type argument for Iterable
. The consequence is that when a specific type (e.g., String
) is used to parameterize Pair
,
that same type value propagates to the type parameter of Iterable
.
for
statement (sometimes called the "for-each loop" statement).
for
statement
The declaration of a generic type can include invocations of itself. Here, a
Pair
invoked with type String
is used as a return type.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
The declaration of a generic type can include invocations of itself. Here, a
Pair
invoked with type String
is used as a return type.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.
Similar to the clause implements Iterable<T>
, above, this is an example
of using the type parameter of the class to invoke another generic type, in this case
Iterator
.
Iterator
takes the place of Enumeration
in the Java Collections Framework. Iterators differ from enumerations in two ways:
Similar to the clause implements Iterable<T>
, above, this is an example
of using the type parameter of the class to invoke another generic type, in this case
Iterator
.
Iterator
takes the place of Enumeration
in the Java Collections Framework. Iterators differ from enumerations in two ways:
This interface is a member of the Java Collections Framework.
Enumeration
can be converted into an Iterator
by using the Enumeration.asIterator()
method.
Here the generic type Pair<T>
is invoked with type argument Integer
.
Integer
class wraps a value of the primitive type int
in an object. An object of type Integer
contains a single field whose type is int
.
Here the generic type Pair<T>
is invoked with type argument Integer
.
Integer
class wraps a value of the primitive type int
in an object. An object of type Integer
contains a single field whose type is int
.
In addition, this class provides several methods for converting an int
to a String
and a String
to an int
, as well as other constants and methods useful when dealing with an int
.
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Implementation note: The implementations of the "bit twiddling" methods (such as highestOneBit
and numberOfTrailingZeros
) are based on material from Henry S. Warren, Jr.'s Hacker's Delight, (Addison Wesley, 2002).
When using a raw type, all type arguments are erased, not just those for the type parameter
of the class. When using a raw Pair
, method asString()
returns another raw Pair
.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.
toString
method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. The string output is not necessarily stable over time or across JVM invocations.
toString
method for class Object
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@
', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Console.charset()
if the Console
exists, stdout.encoding otherwise.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
print(String)
and then println()
.
print(String)
and then println()
.
x
- The Object
to be printed.
The SuppressWarnings
annotation interface is applicable in all declaration contexts, so an @SuppressWarnings
annotation can be used on any element. As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective. For example, if you want to suppress a warning in a particular method, you should annotate that method rather than its class.
The set of warnings suppressed in a given element is a union of the warnings suppressed in all containing elements. For example, if you annotate a class to suppress one warning and annotate a method in the class to suppress another, both warnings will be suppressed in the method. However, note that if a warning is suppressed in a module-info
file, the suppression applies to elements within the file and not to types contained within the module. Likewise, if a warning is suppressed in a package-info
file, the suppression applies to elements within the file and not to types contained within the package.
Java compilers must recognize all the kinds of warnings defined in the Java Language Specification (JLS section 9.6.4.5) which include:
"unchecked"
. "deprecation"
. "removal"
. "preview"
. javac
reference implementation recognizes compilation-related warning names documented in its --help-lint
output.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1
and e2
such that e1.equals(e2)
, and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.
The List
interface places additional stipulations, beyond those specified in the Collection
interface, on the contracts of the iterator
, add
, remove
, equals
, and hashCode
methods. Declarations for other inherited methods are also included here for convenience.
The List
interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList
class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.
The List
interface provides a special iterator, called a ListIterator
, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator
interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.
The List
interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.
The List
interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals
and hashCode
methods are no longer well defined on such a list.
Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException
or ClassCastException
. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.
The List.of
and List.copyOf
static factory methods provide a convenient way to create unmodifiable lists. The List
instances created by these methods have the following characteristics:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. This interface is a member of the Java Collections Framework.
E
- the List
's element type
e1
- the first element
e2
- the second element
List
containing the specified elements
NullPointerException
- if an element is null
Integer
class wraps a value of the primitive type int
in an object. An object of type Integer
contains a single field whose type is int
.
Integer
class wraps a value of the primitive type int
in an object. An object of type Integer
contains a single field whose type is int
.
In addition, this class provides several methods for converting an int
to a String
and a String
to an int
, as well as other constants and methods useful when dealing with an int
.
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Implementation note: The implementations of the "bit twiddling" methods (such as highestOneBit
and numberOfTrailingZeros
) are based on material from Henry S. Warren, Jr.'s Hacker's Delight, (Addison Wesley, 2002).
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.