Search code examples
javagenericswarningsunchecked

How can I avoid unchecked method warnings in Java when I don't know the type of a generic object?


I am new to using Java Generics and am wondering how I should go about getting rid of unchecked method warnings. I understand that code like this specifies the type of the generic object and doesn't give me warnings:

DTRowData<String> someData = new DTRowData<String>("Some string");

But I won't know the type of my generic object, so I have been writing code like this instead:

DTRowData moreData = new DTRowData(80100);

This code makes more sense to me, as it seems like a good reason to use generics is if you don't know what type of data you are going to get back. But it gives me the warning: "Unchecked call to DTRowData as a member of raw type DTRowData"

What is the correct way to stop getting this warning, when I won't know what type of data I'll be getting back? Sometimes it will be a number, sometimes a String. I would prefer not to use

@SuppressWarnings("unchecked")

Here is my class code if it helps at all:

public class DTRowData<E> {
    public E someValue;

    public DTRowDate(E someValue){
        this.someValue = someValue;
    }
}

Solution

  • In the statement DTRowData moreData = new DTRowData(80100);, you already know the type of the parameter E: it is an integer infered from the type of the constructor argument 80100.

    So you can use the generic type as follows:

     DTRowData<Integer> someData = new DTRowData<Integer>(80100);