简体   繁体   English

使用泛型时有关原始类型的Eclipse IDE警告

[英]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(). 我看不出为什么Eclipse在代码行下面会在生成行m1()中创建新的ArrayList的代码下方产生黄色的波浪线(警告)。 When I cannot add a non-String object to the Collection c anyways, why does the IDE wants a <> right next to new ArrayList? 当我仍然无法将非String对象添加到Collection c时,IDE为什么要在新的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(); 警告是给new ArrayList(); , as you are creating ArrayList object without generics. ,因为您要创建没有泛型的ArrayList对象。 Even you have provided generic for reference variable, there are case in which you can add other than String class objects. 即使您为引用变量提供了泛型,在某些情况下您也可以添加String类对象以外的对象。 Like: 喜欢:

You are creating like: Collection<String> c = new ArrayList(); 您正在创建类似: 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. 由于引用具有泛型类型,因此String编译器将仅检查引用,并且不允许使用除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. 这就是为什么它发出警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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