Arrays.asList(arr).indexOf在不起作用

huangapple go评论69阅读模式
英文:

Arrays.asList(arr).indexOf is not working

问题

考虑以下代码片段:

int key1 = Arrays.asList(new int[]{1,2,3,4,5}).indexOf(5); //包装器 
int key2 = new ArrayList<Integer>(Arrays.asList(new int[]{1,2,3,4,5})).indexOf(5); //另一个副本        

但是这个代码片段的评估结果是 -1 -1,这意味着它在列表中没有找到关键字 5。
但是为什么 Arrays.aslist 在列表中找不到关键字呢?有人可以解释一下或者快速修复代码,以在不需要显式逻辑实现的情况下在数组中搜索关键字。当然,我们可以对其进行排序,然后使用 Arrays.binarySearch。还有其他建议或其他方法来实现这一点。

英文:

Consider the following snippet

 int key1 = Arrays.asList(new int[]{1,2,3,4,5}).indexOf(5) ;//wrapper 
 int key2 = new ArrayList&lt;&gt;(Arrays.asList(new int[]{1,2,3,4,5})).indexOf(5); //another copy        

But this snippet evaluates to -1 -1 which means It did not find the key 5 in the list.
But why Arrays.aslist not finding the key in list. Can anyone please explain or quick fix to code for Searching key in array without explicit logic implementation. Of course we can sort it then use Arrays.binarySearch. Any other suggestions or any other ways to do this.

答案1

得分: 0

问题在于您在asList()内部创建的数组类型,考虑到列表类型需要非基本类型,您需要将int声明为Integer。如果您将代码更改为:

Arrays.asList(new Integer[]{1,2,3,4,5}).indexOf(5);

它将起作用。

英文:

The problem is the type of Array you're creating inside the asList(), Considering that the List types require non-primitive types, you need to declare int as Integer. If you change your code to:

Arrays.asList(new Integer[]{1,2,3,4,5}).indexOf(5);

It will work.

huangapple
  • 本文由 发表于 2020年5月5日 20:46:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/61613513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定