Thursday, November 2, 2017

Day 5 - Generics

Generics - Basically, Generics allows you to generalize what you put in the data structures. For example, let's take an example of a LinkedList of Integers. We define it as:

LinkedList intList = new LinkedList<>();

Similarly, we define list of Strings as:

LinkedList stringList = new LinkedList<>();

Suppose we create a method printArray() to print the above lists. We do it by creating two methods:

printArray(LinkedList

printArray(LinkedList

Generics allows to have a Generic datastructure in the following way:

private void printArray(E[] argArray){
  for(E element: argArray){
      System.out.println(element);
 }
}

E can be a Integer, String or any other Object. The limitation here is the element of type is E is limited to operations pertaining to Object such as wait(), notify(), hashCode() etc.

If we need to define a Type in a class to be used in the class, they can be defined as:

class Printer { // Define the Type along with class name.
D arr;
public void  printArray(T[] array) {
for(T element: array){
System.out.println(element);
}

}

}


 



No comments: