Author: saqibkhan

  • Raw Types

    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
    
  • Parameterized Types

    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&lt;Integer, List&lt;String&gt;&gt; box
         = new Box&lt;Integer, List&lt;String&gt;&gt;();
      
      List&lt;String&gt; messages = new ArrayList&lt;String&gt;();
      
      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) {
      this.t = t;
      this.s = s;
    } public T getFirst() {
      return t;
    } public S getSecond() {
      return s;
    } }

    This will produce the following result.

    Output

    Integer Value :10
    String Value :[Hi, Hello, Bye]
    
  • Multiple Type Parameters

    A Generic class can have muliple type parameters. 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&lt;Integer, String&gt; box = new Box&lt;Integer, String&gt;();
      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());
      Box&lt;String, String&gt; box1 = new Box&lt;String, String&gt;();
      box1.add("Message","Hello World");
      System.out.printf("String Value :%s\n", box1.getFirst());
      System.out.printf("String Value :%s\n", box1.getSecond());
    } } 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;
    } }

    This will produce the following result.

    Output

    Integer Value :10
    String Value :Hello World
    String Value :Message
    String Value :Hello World
    
  • Methods

    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();
    } public static void main(String args[]) {
      // Create arrays of Integer, Double and Character
      Integer&#91;] intArray = { 1, 2, 3, 4, 5 };
      Double&#91;] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
      Character&#91;] charArray = { 'H', 'E', 'L', 'L', 'O' };
      System.out.println("Array integerArray contains:");
      printArray(intArray);   // pass an Integer array
      System.out.println("\nArray doubleArray contains:");
      printArray(doubleArray);   // pass a Double array
      System.out.println("\nArray characterArray contains:");
      printArray(charArray);   // pass a Character array
    } }

    This will produce the following result −

    Output

    Array integerArray contains:
    1 2 3 4 5 
    
    Array doubleArray contains:
    1.1 2.2 3.3 4.4 
    
    Array characterArray contains:
    H E L L O
    
  • Type Inference

    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&lt;Integer&gt; integerBox = new Box&lt;&gt;();
      //unchecked conversion warning
      Box&lt;String&gt; stringBox = new Box&lt;String&gt;();
      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));
      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.get());
    } } class Box<T> { private T t; public void add(T t) {
      this.t = t;
    } public T get() {
      return t;
    } }

    This will produce the following result.

    Output

    Integer Value :10
    String Value :Hello World
    
  • Type Parameter Naming Conventions

    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&lt;Integer, String&gt; box = new Box&lt;Integer, String&gt;();
      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&lt;String, Integer&gt; pair = new Pair&lt;String, Integer&gt;(); 
      pair.addKeyValue("1", Integer.valueOf(10));
      System.out.printf("(Pair)Integer Value :%d\n", pair.getValue("1"));
      CustomList&lt;Box&gt; list = new CustomList&lt;Box&gt;();
      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
  • Classes

    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&lt;Integer&gt; integerBox = new Box&lt;Integer&gt;();
      Box&lt;String&gt; stringBox = new Box&lt;String&gt;();
      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));
      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.get());
    } } class Box<T> { private T t; public void add(T t) {
      this.t = t;
    } public T get() {
      return t;
    } }

    This will produce the following result.

    Output

    Integer Value :10
    String Value :Hello World
    
  • Environment Setup

    Local Environment Setup

    JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine.

    System Requirement

    JDK1.5 or above.
    MemoryNo minimum requirement.
    Disk SpaceNo minimum requirement.
    Operating SystemNo 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.

    OSTaskCommand
    WindowsOpen Command Consolec:\> java -version
    LinuxOpen Command Terminal$ java -version
    MacOpen Terminalmachine:< joseph$ java -version

    Let’s verify the output for all the operating systems −

    OSOutput
    Windowsjava 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)
    Linuxjava 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)
    Macjava 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.

    OSOutput
    WindowsSet the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21
    Linuxexport JAVA_HOME = /usr/local/java-current
    Macexport JAVA_HOME = /Library/Java/Home

    Append Java compiler location to the System Path.

    OSOutput
    WindowsAppend the string C:\Program Files\Java\jdk1.6.0_21\bin at the end of the system variable, Path.
    Linuxexport PATH = $PATH:$JAVA_HOME/bin/
    Macnot required

    Verify Java installation using the command java -version as explained above.

  • Overview

    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.

  • ConcurrentNavigableMap Interface

    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
    1NavigableSet<K> descendingKeySet()Returns a reverse order NavigableSet view of the keys contained in this map.
    2ConcurrentNavigableMap<K,V> descendingMap()Returns a reverse order view of the mappings contained in this map.
    3ConcurrentNavigableMap<K,V> headMap(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
    4ConcurrentNavigableMap<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.
    5NavigableSet<K> keySet()Returns a NavigableSet view of the keys contained in this map.
    6NavigableSet<K> navigableKeySet()Returns a NavigableSet view of the keys contained in this map.
    7ConcurrentNavigableMap<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.
    8ConcurrentNavigableMap<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.
    9ConcurrentNavigableMap<K,V> tailMap(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
    10ConcurrentNavigableMap<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&lt;String,String&gt; map =
         new ConcurrentSkipListMap&lt;String, String&gt;();
      map.put("1", "One");
      map.put("2", "Two");
      map.put("3", "Three");
      map.put("5", "Five");
      map.put("6", "Six");
      System.out.println("Initial ConcurrentHashMap: "+map);
      System.out.println("HeadMap(\"2\") of ConcurrentHashMap: "+map.headMap("2"));
      System.out.println("TailMap(\"2\") of ConcurrentHashMap: "+map.tailMap("2"));
      System.out.println(
         "SubMap(\"2\", \"4\") of ConcurrentHashMap: "+map.subMap("2","4"));
    } }

    This will produce the following result.

    Output

    Initial ConcurrentHashMap: {1 = One, 2 = Two, 3 = Three, 5 = Five, 6 = Six}
    HeadMap("2") of ConcurrentHashMap: {1 = One}
    TailMap("2") of ConcurrentHashMap: {2 = Two, 3 = Three, 5 = Five, 6 = Six}
    SubMap("2", "4") of ConcurrentHashMap: {2 = Two, 3 = Three}