A raw type is an object of a generic class or interface if its type arguments are not passed during its creation. Following example will showcase above mentioned concept.
Example
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer> box = new Box<Integer>();
box.set(Integer.valueOf(10));
System.out.printf("Integer Value :%d\n", box.getData());
Box rawBox = new Box();
//No warning
rawBox = box;
System.out.printf("Integer Value :%d\n", rawBox.getData());
//Warning for unchecked invocation to set(T)
rawBox.set(Integer.valueOf(10));
System.out.printf("Integer Value :%d\n", rawBox.getData());
//Warning for unchecked conversion
box = rawBox;
System.out.printf("Integer Value :%d\n", box.getData());
}
}
class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T getData() {
return t;
}
}
This will produce the following result.
Output
Integer Value :10
Integer Value :10
Integer Value :10
Integer Value :10
A Generic class can have parameterized types where a type parameter can be substituted with a parameterized type. Following example will showcase above mentioned concept.
Example
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer, List<String>> box
= new Box<Integer, List<String>>();
List<String> messages = new ArrayList<String>();
messages.add("Hi");
messages.add("Hello");
messages.add("Bye");
box.add(Integer.valueOf(10),messages);
System.out.printf("Integer Value :%d\n", box.getFirst());
System.out.printf("String Value :%s\n", box.getSecond());
}
}
class Box<T, S> {
private T t;
private S s;
public void add(T t, S s) {
You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method’s return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic method’s body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).
Example
Following example illustrates how we can print an array of different type using a single Generic method −
public class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
Type inference represents the Java compiler’s ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters.
Compiler generates unchecked conversion warning in-case type inference is not used.
Syntax
Box<Integer> integerBox = new Box<>();
Where
Box − Box is a generic class.
<> − The diamond operator denotes type inference.
Description
Using diamond operator, compiler determines the type of the parameter. This operator is avalilable from Java SE 7 version onwards.
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
Example
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
//type inference
Box<Integer> integerBox = new Box<>();
//unchecked conversion warning
Box<String> stringBox = new Box<String>();
By convention, type parameter names are named as single, uppercase letters so that a type parameter can be distinguished easily with an ordinary class or interface name. Following is the list of commonly used type parameter names −
E − Element, and is mainly used by Java Collections framework.
K − Key, and is mainly used to represent parameter type of key of a map.
V − Value, and is mainly used to represent parameter type of value of a map.
N − Number, and is mainly used to represent numbers.
T − Type, and is mainly used to represent first generic type parameter.
S − Type, and is mainly used to represent second generic type parameter.
U − Type, and is mainly used to represent third generic type parameter.
V − Type, and is mainly used to represent fourth generic type parameter.
Following example will showcase above mentioned concept.
Example
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer, String> box = new Box<Integer, String>();
box.add(Integer.valueOf(10),"Hello World");
System.out.printf("Integer Value :%d\n", box.getFirst());
System.out.printf("String Value :%s\n", box.getSecond());
Pair<String, Integer> pair = new Pair<String, Integer>();
pair.addKeyValue("1", Integer.valueOf(10));
System.out.printf("(Pair)Integer Value :%d\n", pair.getValue("1"));
CustomList<Box> list = new CustomList<Box>();
list.addItem(box);
System.out.printf("(CustomList)Integer Value :%d\n", list.getItem(0).getFirst());
}
}
class Box<T, S> {
private T t;
private S s;
public void add(T t, S s) {
this.t = t;
this.s = s;
}
public T getFirst() {
return t;
}
public S getSecond() {
return s;
}
}
class Pair<K,V>{
private Map<K,V> map = new HashMap<K,V>();
public void addKeyValue(K key, V value) {
map.put(key, value);
}
public V getValue(K key) {
return map.get(key);
}
}
class CustomList<E>{
private List<E> list = new ArrayList<E>();
public void addItem(E value) {
list.add(value);
}
public E getItem(int index) {
return list.get(index);
}
}
This will produce the following result.
Output
Integer Value :10
String Value :Hello World
(Pair)Integer Value :10
(CustomList)Integer Value :10
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.
Syntax
public class Box<T> {
private T t;
}
Where
Box − Box is a generic class.
T − The generic type parameter passed to generic class. It can take any Object.
t − Instance of generic type T.
Description
The T is a type parameter passed to the generic class Box and should be passed when a Box object is created.
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
Example
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine.
System Requirement
JDK
1.5 or above.
Memory
No minimum requirement.
Disk Space
No minimum requirement.
Operating System
No minimum requirement.
Step 1: Verify Java Installation in Your Machine
First of all, open the console and execute a java command based on the operating system you are working on.
OS
Task
Command
Windows
Open Command Console
c:\> java -version
Linux
Open Command Terminal
$ java -version
Mac
Open Terminal
machine:< joseph$ java -version
Let’s verify the output for all the operating systems −
OS
Output
Windows
java version “1.6.0_21″Java(TM) SE Runtime Environment (build 1.6.0_21-b07)Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Linux
java version “1.6.0_21″Java(TM) SE Runtime Environment (build 1.6.0_21-b07)Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Mac
java version “1.6.0_21″Java(TM) SE Runtime Environment (build 1.6.0_21-b07)Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)
If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.6.0_21 as the installed version for this tutorial.
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
Step 2: Set JAVA Environment
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example.
OS
Output
Windows
Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21
Linux
export JAVA_HOME = /usr/local/java-current
Mac
export JAVA_HOME = /Library/Java/Home
Append Java compiler location to the System Path.
OS
Output
Windows
Append the string C:\Program Files\Java\jdk1.6.0_21\bin at the end of the system variable, Path.
Linux
export PATH = $PATH:$JAVA_HOME/bin/
Mac
not required
Verify Java installation using the command java -version as explained above.
It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.
A java.util.concurrent.ConcurrentNavigableMap interface is a subinterface of ConcurrentMap interface, and supports NavigableMap operations, and recursively so for its navigable sub-maps, and approximate matches.
ConcurrentMap Methods
Sr.No.
Method & Description
1
NavigableSet<K> descendingKeySet()Returns a reverse order NavigableSet view of the keys contained in this map.
2
ConcurrentNavigableMap<K,V> descendingMap()Returns a reverse order view of the mappings contained in this map.
3
ConcurrentNavigableMap<K,V> headMap(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
4
ConcurrentNavigableMap<K,V> headMap(K toKey, boolean inclusive)Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
5
NavigableSet<K> keySet()Returns a NavigableSet view of the keys contained in this map.
6
NavigableSet<K> navigableKeySet()Returns a NavigableSet view of the keys contained in this map.
7
ConcurrentNavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)Returns a view of the portion of this map whose keys range from fromKey to toKey.
8
ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
9
ConcurrentNavigableMap<K,V> tailMap(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
10
ConcurrentNavigableMap<K,V> tailMap(K fromKey, boolean inclusive)Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.
Example
The following TestThread program shows usage of ConcurrentNavigableMap.
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class TestThread {
public static void main(final String[] arguments) {
ConcurrentNavigableMap<String,String> map =
new ConcurrentSkipListMap<String, String>();