javagenericsgeneric-method

How to create a generic method that accepts only generic parameters and not raw type parameters?


I want to create a generic method that accepts only an arraylist of integers. But the method is also accepting a raw type. How can I restrict it to accept only an arraylist of integers?

package generics;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class GenericBox<T> {
    public static void main(String[] args) {
        ArrayList l1 = new ArrayList();
        l1.add(1);
        l1.add("subbu");
        printListValues(l1);

        ArrayList<Integer> l2 = new ArrayList<>();
        l2.add(1);
        l2.add(2);
        printListValues(l2);
    }
    public static <T extends ArrayList<Integer>> void printListValues(T t){
        System.out.println(t);
    }
}

Thank you, Subbu.


Solution

  • But the method is also accepting a raw type

    Are you saying that you want this call to be forbidden ?

    printListValues(new ArrayList());  // raw type
    

    The compiler will issue a warning about using raw types, but it will compile. You might be able to tell your compiler (examine its documentation or configuration GUI for how) to treat this as an error, and so forbid it.

    The reason the compiler normally allows this is backwards-compatibility. Generics were added later in life (with Java 5) and are "opt-in". If the code uses generic types, they have to be correct, but you could forgo that altogether. The old "raw" code still continues to work (which is a strong selling point of Java).

    Maybe there is a compiler option to turn warnings into errors, so you can prevent yourself from using raw types. But you cannot force others to do that.