【问题标题】:Find an integer in an Array in a short manner in Java在Java中以简短的方式在数组中查找整数
【发布时间】:2014-02-06 11:10:50
【问题描述】:

我已经尝试过这篇文章: 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));

任何帮助将不胜感激

【问题讨论】:

  • 该链接上的第一个答案指出当 int[]Arrays.asList 时会发生什么(以及为什么它没有按照您的意愿行事)...

标签: java arrays list hashmap instantiation


【解决方案1】:

改变

int[] temp = ...

Integer[] temp = ...

【讨论】:

    【解决方案2】:

    int 更改为 Integer,因为您将具有泛型的 List 声明为 Integer

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

    【讨论】:

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

      【讨论】:

        【解决方案4】:

        假设您要问的真正问题是“如何在 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)
        }
        

        【讨论】:

          【解决方案5】:

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

           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];         
           }
          

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

          【讨论】:

          • binary search 代替呢?最多占用 log n。您甚至可以在 Arrays#binarySearch 中获得免费的 impl。
          • 这需要排序。对于简单循环,排序是 O(N log N)(充其量)与普通的 O(N)。这个问题主要是关于“短”(我假设代码行的数量),我只是提出这个答案来指出“只是做它”大约只要通过长度来做某事的副产品别的。如果目标是性能,则需要更多上下文来选择最佳方法。
          • 好的。该列表在问题中排序,但也许这只是偶然的。
          猜你喜欢
          • 2017-09-07
          • 2015-05-13
          • 2017-04-15
          • 1970-01-01
          • 1970-01-01
          • 2017-04-27
          • 2014-12-21
          • 2020-10-29
          • 1970-01-01
          相关资源
          最近更新 更多