0

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;
    }
}
jabe
  • 784
  • 2
  • 15
  • 33
  • 3
    [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Sotirios Delimanolis Feb 20 '15 at 18:21
  • 1
    Generally we use `>` wildcard if we don't know specific type. You can also let compiler infer type with diamond operator `<>`. But in case of `new DTRowData(80100)` why not just use ``? – Pshemo Feb 20 '15 at 18:22
  • 1
    What do you mean by "no idea"? Will you be passed `Object`s only? – fge Feb 20 '15 at 18:25

1 Answers1

3

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);
M A
  • 71,713
  • 13
  • 134
  • 174