Java / Generics
Generic method are methods that is type parameterized.
public class GenericMethodExample { public static void main(String[] s) { String[] StrArray = new String[] { "Find", "the", "word", "in", "this", "Array" }; System.out.println(contains(StrArray, "word")); Integer[] intArray = new Integer[] { 4, 5, 32, 100, 303, 2002, 465 }; System.out.println(contains(intArray, 2002)); } public static <T> boolean contains(T[] list, T itemToFind) { for (T listItem : list) { if (itemToFind == null) { if (listItem == null) return true; } else if (itemToFind.equals(listItem)) { return true; } } return false; } }
Generics introduced in Java 1.5, facilitates strong-typing on the collection objects. Generics defines the object types that the collection can hold.
It provides compile time type-safety and ensures that only the particular type is added in collection and eliminates ClassCastException in runtime.
List list = new ArrayList(); list.add("No Generics is used "); String s = (String) list.get(0);
In the above example, ArrayList can hold any type of objects, however we need to cast each object to its appropriate data type since get method's return type is Object. A string literal is added to the list and to get it from the list we need cast and store it.
If we store an employee object for example at the first index, then the 3rd line of code will throw a run-time Exception.
List<String> list = new ArrayList<String>(); list.add("Generics is implemented"); String s = list.get(0); // no cast is required
In the above code, the example is rewritten using generics, and the list is strongly typed that requires no casting.
Generic types refers to generic class, abstract class or interface that is parameterized.
using @SuppressWarnings("unchecked") annotation.
@SuppressWarnings("unchecked") List<String> myList = new ArrayList();
static <T extends Number> T processTheNumber(T number){ T result = number; return result; }
Replace all the raw type with the generic types like E,K, V etc and also add the list of generic types before the return type using <>.
public <K,V> V StoreThePair(K key, V value) { return V; }
- Helps creating type-safe collections objects.
- Facilitate Strong type validation during the compile-time.
- Eliminates Cast operator.
- mproves the performance as Generics eliminates casting, boxing/unboxing.
- Enables creation of generic algorithms, customizing the algorithm to be compatible with collection of different types, that are type-safe.
The Generic types are defined as <"GenericType"> e.g.
Generics helps finding issues during compile time rather than runtime. Generics are parameter for types.
Type erasure refers to the compile-time process where compiler erases type information during compile time and no type is available at runtime.
Collections.sort() that sorts collection of elements or objects of any type is a generic method.
Bounded Wildcards impose bound on Type.
There are two types of Bounded wild-cards.
- <? extends T>
- <? super T>
Bounded wildcards are specified by List<? extends SuperClassType>
Bounded wildcards <? extends T> which impose an upper bound by ensuring that type must be sub class of T.
<? super T> imposes lower bound by ensuring Type must be super class of T.
Arrays does not support generics.
No. We encounter compilation error as it is incompatible.
You may add a new Objects or its sub-type into List whereas you could only insert null into the List<?>
Also known as Collection of Unknown type, specified using the wildcard character(?). for e.g., List> , Collection>.
An example of unbounded wildcards.
public static void printCollection(List<?> myList) { for (Object key: myList) { System.out.print(key + " "); } }
It is applicable when your method does not to have to do anything with the individual element types, for e.g. it can be used to determine the length of the list of any type.
The SuppressWarning annotation is used to suppress compiler warning for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.
Raw type refers to generic type without specifying any parametrized type. For example, List is a raw type while List