在单行上创建项目列表,然后查询列表以查看项目是否存在,而不会收到 Java 中未经检查的转换警告
我想要一个事物列表,然后我想测试该列表以查看某个项目是否存在:
这是我的示例片段:
String[] handToolArray = {"pliers", "screwdriver", "tape measure"};
List<String> handToolList = new ArrayList<String>( Arrays.asList(handToolArray));
if (handToolList.contains("pliers")){
System.out.println("I have pliers");
} else {
System.out.println("I don't have pliers");
}
在第二行中, Arrays.asList(handToolArray) 生成:
"Type safety: The expression of type List needs unchecked conversion to conform to Collection<? extends String>"
问题: 有没有更好的方法来创建然后查询列表,即简洁并且不需要抑制未经检查的警告?
I want a list of things, and then I want to test the list to see if an item exists:
Here is my example snippet:
String[] handToolArray = {"pliers", "screwdriver", "tape measure"};
List<String> handToolList = new ArrayList<String>( Arrays.asList(handToolArray));
if (handToolList.contains("pliers")){
System.out.println("I have pliers");
} else {
System.out.println("I don't have pliers");
}
In the second line, the Arrays.asList(handToolArray) generates:
"Type safety: The expression of type List needs unchecked conversion to conform to Collection<? extends String>"
Question:
Is there a better way to create then query the list, that is succinct and does not require unchecked warnings to be suppressed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在不显式构造数组的情况下完成此操作(可变参数仍然使用数组)。
You can do it without explicitly constructing an array (arrays are still used by varargs).
首先,我没有收到类型安全警告,你也不应该收到。你使用什么Java编译器?
Arrays.asList 已经创建了一个 ArrayList (由原始数组支持),所以如果您不需要副本,您可以这样做
另请注意,像 Apache Commons Lang ArrayUtils 这样的东西具有直接检查数组中是否存在元素的函数:
First of all, I do not get the type safety warning, and neither should you. What Java compiler are you using?
Arrays.asList already creates an ArrayList (backed by the original array), so if you do not need a copy, you can just do
Also note that something like Apache Commons Lang ArrayUtils has functions to check if an element exists in an array directly:
请注意,List 接口定义了
indexOf()
方法,您可以使用该方法来检查某些内容是否存在:Note the List interface defines the
indexOf()
method, which you can use to check if something exists: