Java通用用法格式

时间:2015-07-10 23:04:22

标签: java generics

当我需要创建一个需要存储字符串的ArrayList时,我这样做 -

ArrayList<String> whatwhat = new ArrayList<String>();

在eclipse中,当我从上述陈述的左侧或右侧省略时,我收到警告。这让我想到了我的问题,为什么Java需要/允许这个?难道我们不应该只在一边说明Generic类型吗?

3 个答案:

答案 0 :(得分:4)

使用Java 6及之前的版本,您需要在双方输入的内容。

但是,starting with Java 7, you can use the "diamond operator",右侧是空角括号<>,编译器会根据左侧的类型参数推断出类型。

ArrayList<String> whatwhat = new ArrayList<>();  // Java 7+

答案 1 :(得分:1)

正如您所看到的那样,没有错误,因此您可以确保javac允许这样做。现在,您正在收到警告,因此这与Eclipse提供的功能有关。

实际上,Eclipse提供了这些类型的功能来警告(或者给出错误,如果开发人员已经为Eclipse配置了相同的),那么你正在使用旧的约定,并且应该更新。

解决方案:
您可能希望更改Eclipse设置,如下所示,您的警告应该消失。

enter image description here

答案 2 :(得分:0)

Well no. See is that on the left hand side, you are using the generic type ArrayList where on the right side you are using the raw type ArrayList(); . You can add a whatwhat.add("new:); and Java will automatically warp "new" into new String. This is called autoboxing. While casting is not needed to retrieve a value from a list with a specified element type, because the compiler already knows the element type. The reason you are getting an error when you don’t have on the right, is because it must

ArrayList<String> whatwhat = new ArrayList<>(); ... // some list that contains some strings
ArrayList<String> whatwhat = new ArrayList<String>(); ... // Legal since you used the raw type and lost all type checking