java 中通用对象的 ArrayList。作为原始类型 'Class' 的成员未经检查地调用 'Class(T)'
ArrayList of generic objects in java. Unchecked call to 'Class(T)' as a member of raw type 'Class'
我有如下一段代码:
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)
或任何需要的类型,您可以避免该问题。
在您的数组列表中,您放置了 Number
以及 String
。
即你在你的数组列表中添加对象,所以它的类型应该是 Object
因为它是java中所有类的parent
。
List<Coordinate<Object>> location = new ArrayList<Coordinate<Object>>();
我有如下一段代码:
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)
或任何需要的类型,您可以避免该问题。
在您的数组列表中,您放置了 Number
以及 String
。
即你在你的数组列表中添加对象,所以它的类型应该是 Object
因为它是java中所有类的parent
。
List<Coordinate<Object>> location = new ArrayList<Coordinate<Object>>();