简体   繁体   English

是ArrayList中的值 <Integer> ? (Java)

[英]Is value in ArrayList<Integer>? (Java)

In Java, I'm trying to know whether an Integer is in an ArrayList<Integer> . 在Java中,我试图知道ArrayList<Integer>是否存在Integer I tried using this general solution , which warns that it doesn't work with arrays of primitives . 我尝试使用这个一般的解决方案 ,警告称它不适用于基本数组 That shouldn't be a problem, since Integer s aren't primitives ( int s are). 这应该不成问题,因为Integer不是原语( int是)。

ArrayList<Integer> ary = new ArrayList<Integer>();
ary.add(2);

System.out.println(String.format("%s", Arrays.asList(ary).contains(2)));

Returns false . 返回false Any reason why? 有什么原因吗? Any help is appreciated, although the less verbose the better. 感谢任何帮助,尽管详细程度越低越好。

Any reason why it returns false ? 它返回false任何原因?

Simply because Arrays.asList(ary) will return a List<ArrayList<Integer>> and you try to find if it contains an Integer which cannot work. 仅仅因为Arrays.asList(ary)将返回List<ArrayList<Integer>>并且您尝试查找它是否包含无法使用的Integer

As remainder here is the Javadoc of Arrays.asList(ary) 剩下的就是Arrays.asList(ary)的Javadoc

public static <T> List<T> asList(T... a) Returns a fixed-size list backed by the specified array. public static <T> List<T> asList(T... a)返回由指定数组支持的固定大小的列表。

Here as you provide as argument an ArrayList<Integer> , it will return a List of what you provided so a List<ArrayList<Integer>> . 在这里,当您提供ArrayList<Integer>作为参数时,它将返回您提供的内容的List ,即List<ArrayList<Integer>>

You need to call List#contains(Object) on your list something like ary.contains(myInteger) . 您需要在列表上调用List#contains(Object) ,例如ary.contains(myInteger)

You don't need asList() as ArrayList itself a list. 您不需要asList()作为ArrayList本身就是一个列表。 Also you don't need String.format() to print the result. 另外,您不需要String.format()即可打印结果。 Just do in this way. 只是这样做。 This returns true : 返回true

System.out.println(ary.contains(2));

The problem is that you're trying to coerce your ArrayList to a List when it already is. 问题是您正在尝试将ArrayList强制转换为List。 Arrays.asList takes an array or variable number of arguments and adds all of these to a list. Arrays.asList采用数组或可变数量的参数,并将所有这些参数添加到列表中。 All you need to do is call System.out.println(ary.contains(2)); 您所需要做的就是调用System.out.println(ary.contains(2));。

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

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