Generic Methods

Generic Methods

1. m1(ArrayList<String>)

It is applicable for ArrayList of only String type.

2. m1(ArrayList<? extends x> l)

Here if ‘x’ is a class then this method is applicable for ArrayList of either x or it’s child classes.

If ‘x’ is an interface then this method is applicable for ArrayList of any implementation class of x

3. m1(ArrayList <? Super x> l)

If ‘x’ is a class then this method is applicable for ArrayList of either x or it’s super classes.

If ‘x’ is an interface then this method is applicable for ArrayList of any super classes of implemented class of x.

4. m1(ArrayList <?> l)

This method is applicable for ArrayList of any type.

In the method declaration if we can use ‘?’ in that method we are not allowed to insert any element except null. Because we don’t know exactly what type of object is coming.

import java.util.ArrayList;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyGenericMethod {
   public static void main(String arg[]) {
      ArrayList<String> list1 = new ArrayList<String>();
      list1.add("A");
      list1.add("B");
      list1.add("C");
      list1.add("D");
      m1(list1);
 
      ArrayList<Integer> list2 = new ArrayList<Integer>();
      list2.add(10);
      list2.add(20);
      list2.add(30);
      list2.add(40);
      m1(list2);
   }

   public static void m1(ArrayList<?> list) {
      // list.add("D"); C.E: Because we can’t expect what type of value will come
      list.remove(1);
      list.add(null);
      System.out.println(l);
   }
}

Output

[A, C, D, null]
[10, 30, 40, null]

Note

Generics is the concept applicable only at compile time to provide type safety, at run time there is no generic concept at all.

Generic Methods


Scroll to top