简体   繁体   中英

Eclipse IDE warnings about Raw types when using Generics

I see no reason why Eclipse produces yellow squiggly lines(warning) underneath the line of code where Im creating a new ArrayList inside method m1(). When I cannot add a non-String object to the Collection c anyways, why does the IDE wants a <> right next to new ArrayList? At execution time, they are type erased also so trying to understand if it really means anything.

import java.util.ArrayList;
import java.util.Collection;

public class Main {

    public static void main(String[] args) {
        m1();
    }

    private static  Collection<String> m1() {
        Collection<String> c = new ArrayList();//gives typesafety warning for missing <>
        c.add("A");
        c.add("B");
        c.add(1); // does not let me add a non-String type anyways
        return c;
    }
}

The warning is giving for new ArrayList(); , as you are creating ArrayList object without generics. Even you have provided generic for reference variable, there are case in which you can add other than String class objects. Like:

You are creating like: Collection<String> c = new ArrayList(); . As the reference is having generic type String compiler will check only reference and will not allow anything other than string. But in case:

Collection<Integer> intColl = (Collection)c;

In this case you can even add integer in collection. That's why it is giving the warning.

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