简体   繁体   中英

instantiating parameterized class

Just wondering if this is the right way to do it. I want to construct instances of my parametrized class where one of the instance variables is a generic type. The code below works but I get a lot of warnings in the main method "SomeObject is a raw type. References to generic type SomeObject should be parameterized".

public class SomeObject<T> {

    private String description;

    private T value;


    public SomeObject(String description, T value) {
        this.description = description;
        this.value = value;
    }



public static void main(String args[]){

    List <SomeObject> objectList = new ArrayList<SomeObject>();

    objectList.add(new SomeObject("Object 1: ", true));
    objectList.add(new SomeObject("Object 2: ", 888.00));
    objectList.add(new SomeObject("Object 3: ", "another object"));
    objectList.add(new SomeObject("Object 4: ", '4'));

    for (SomeObject object : objectList){
    System.out.println(object.getDescription() + object.getValue());
    }
}

}

The code below works but I get a lot of warnings in the main method "Object is a raw type. References to generic type Object should be parameterized".

the warning is because you haven't specified the type arguments when constructing the SomeObject . ie.

it should be:

List<SomeObject<?>> objectList = new ArrayList<>();
objectList.add(new SomeObject<Boolean>("Object 1: ", true));
objectList.add(new SomeObject<Double>("Object 2: ", 888.00));
objectList.add(new SomeObject<String>("Object 3: ", "another object"));
objectList.add(new SomeObject<Character>("Object 4: ", '4'));

When you have a SomeObject without a type argument (the part in the square brackets), that is called a raw type , and it's the same as using the erasure of SomeObject . (Basically, the erasure means it's non-generic.)

You also need to provide a type argument to the SomeObject part of the List . Here I've used a wildcard, which means the list can hold any type of SomeObject , but once we put a SomeObject in to the list we don't know what their original type argument was anymore:

List<SomeObject<?>> objectList = new ArrayList<SomeObject<?>>();

objectList.add(new SomeObject<Boolean>("Object 1: ", true));
objectList.add(new SomeObject<Double>("Object 2: ", 888.00));
objectList.add(new SomeObject<String>("Object 3: ", "another object"));
objectList.add(new SomeObject<Character>("Object 4: ", '4'));

for (SomeObject<?> object : objectList) {
    ...;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM