转换原始int数组列出 [英] Converting Primitive int array to list
问题描述
我试图解决以下问题。有两个数组大小n和大小为n + 1的B。 A和B的所有元素相同。 B有一个额外的元素。找到的元素。
I am trying to solve the following problem. There are two arrays A of size n and B of size n+1. A and B have all elements same. B has one extra element. Find the element.
我的逻辑是将数组转换为列表并检查B中每个元素是present于A。
My logic is to convert the array to list and check if each element in B is present in A.
但是,当我使用的基本数组我的逻辑是行不通的。如果我使用
But when I am using the primitive arrays my logic is not working. If I am using
Integer [] a ={1,4,2,3,6,5};
Integer [] b = {2,4,1,3,5,6,7};
我的code是工作的罚款。
My code is working fine.
public static void main(String [] args)
{
int [] a ={1,4,2,3,6,5};
int [] b = {2,4,1,3,5,6,7};
List<Integer> l1 = new ArrayList(Arrays.asList(a));
List<Integer> l2 = new ArrayList(Arrays.asList(b));
for(Integer i :l2)
{
if(!l1.contains(i))
{
System.out.println(i);
}
}
}
也是我的逻辑是O(n + 1)。有没有更好的算法中。
And also My logic is O(n+1). Is there any better algo.
感谢
推荐答案
这是不工作的基本数组的原因,就是 Arrays.asList 定当 INT [] 返回列表&LT;整数[]> 而不是一个名单,其中,整型>
The reason it is not working for primitive arrays, is that Arrays.asList when given an int[ ] returns a List<Integer[ ]> rather than a List<Integer>.
番石榴已经在Ints 的类。是有一个 asList 方法,将采取 INT [] ,然后返回一个列表&LT;整数>
Guava has an answer to this in the Ints class. Is has an asList method that will take an int[ ] and return a List<Integer>
更新
int[] a = ...;
int[] b = ...;
List<Integer> aList = Ints.asList(a);
List<Integer> bList = Ints.asList(b);
以上将让您的code正常工作对于int [],因为它适用于整数[]。
The above will allow your code to work properly for int[ ] as it works for Integer[ ].
查看 INTS API
这篇关于转换原始int数组列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!