在Java中以简短的方式在Array中查找整数

时间:2014-01-17 07:48:37

标签: java arrays list hashmap instantiation

我已经尝试过这篇文章: Java, Simplified check if int array contains int

并尝试了这个

int[] temp = {3,9,15,21,27,33,39};
HashSet<Integer> otherBy3 = new HashSet<Integer>(Arrays.asList(temp));

基于我在上述链接上看到的帖子,指示我这样做:

HashSet<Integer> set= new HashSet<Integer>(Arrays.asList(intArray));
set.contains(intValue)

但我一直收到此错误

cannot find symbol
symbol  : constructor HashSet(java.util.List<int[]>)
location: class java.util.HashSet<java.lang.Integer> HashSet<Integer> otherBy3 = new HashSet<Integer>(Arrays.asList(temp));

任何帮助将不胜感激

5 个答案:

答案 0 :(得分:2)

更改

int[] temp = ...

Integer[] temp = ...

答案 1 :(得分:2)

Integer[] temp = {3,9,15,21,27,33,39};
HashSet<Integer> set= new HashSet<Integer>(Arrays.asList(temp));
System.out.println(set.contains(3));

答案 2 :(得分:1)

int 更改为整数,因为您要将列表声明为通用整数

Integer[] temp = new Integer[] { 3, 9, 15, 21, 27, 33, 39 };
HashSet<Integer> otherBy3 = new HashSet<Integer>(Arrays.asList(temp));
otherBy3.contains(13);

答案 3 :(得分:1)

告诉你真正的问题是“如何在int []数组中找到一个整数”,为什么不使用Arrays.html#binarySearch。它是一个单线程,非常快的O(log n)并且是这种做法的常用方法。唯一的预先要求是您的列表已经排序,而您的列表似乎是(不是吗?)。

int[] temp = {3,9,15,21,27,33,39};
int k = 28;    //Not present in temp
if (Arrays.binarySearch(temp, k) > 0) {
    //key found
}
else {
    //key not found - returns -5 (negative indicating not found)
}

答案 4 :(得分:0)

我觉得有点令人不安的是,构建几个临时对象被认为比简单的怪异循环“更短”:

 int[] temp = {3,9,15,21,27,33,39};
 boolean found = false;
 for (int i=0; i<temp.length && !found; ++i) {
     found = valueToFind == temp[i];         
 }

与高开销方法的代码量大致相同。

相关问题