我有以下代码:
public class Coordinate<T>{
T coordinate;
//rest of class
}
然后我稍后尝试创建一个包含各种坐标的 ArrayList,如下所示:
ArrayList<Coordinate> location = new ArrayList<Coordinate>();
最后我向该位置添加一些坐标
location.add(new Coordinate(0));
location.add(new Coordinate("A"));
location.add(new Coordinate(0.1f));
这些 location.add() 调用给了我以下警告:
Unchecked call to 'Coordinate(T)' as a member of raw type 'Coordinate'
我已经搜索了这个警告并发现了一些命中,但我无法从这些答案中找出如何使我的应用程序工作,因为我希望 ArrayList 位置能够保存不同类型的坐标,所以我不能做类似的事情
ArrayList<Coordinate<Integer>> location = new ArrayList<Coordinate<Integer>>();
。
也许我只是以错误的方式解决这个问题?
提前致谢。
最佳答案
如果您只想混合数字,可以使用以下内容( <>
是 Java 7 及更高版本中的菱形,对于早期版本,没有类型推断)。
List<Coordinate<? extends Number>> location = new ArrayList<>();
location.add(new Coordinate<>(1));
location.add(new Coordinate<>(1.0));
如果您想使用各种对象,可以使用以下内容:
List<Coordinate<?>> location = new ArrayList<>();
location.add(new Coordinate<>(1));
location.add(new Coordinate<>("Hello"));
自从您创建Coordinate
以来没有通用参数的对象,您会收到警告。
new Coordinate(0) -> Unchecked call to 'Coordinate(T)' as a member of raw type 'Coordinate'
通过更改 Coordinate
的创建至new Coordinate<>(1)
或者您需要避免该问题的任何类型。
关于java - java中通用对象的ArrayList。作为原始类型 'Class(T)' 的成员对 'Class' 进行未经检查的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27859088/