【问题标题】:arrange index of elements with highest double value in array排列数组中具有最高双精度值的元素的索引
【发布时间】:2016-12-08 23:33:45
【问题描述】:

所以我有一个包含 30 个概率值的数组作为两倍。我想要

  1. 首先检查数组中的最高元素
  2. 将其索引存储在新数组中
  3. 重复第一步,排除之前检查过的元素

我试图通过将选中的元素替换为 null 并通过检查除 null 之外的所有元素来重复步骤 1 来做到这一点。但这给了我空指针异常。即使我正在创建 Array 的 Double 对象。

Double[] P_array= {0.23, 0.45, 0.1, 0.65, 0.67};
int maxIndex = 0;
int[] index_sorting  = new int[P_array.length]; 
int sort_index  = 0; 
for (int i = 1; i < P_array.length; i++){
    if (P_array[i] != (null)){    //getting NPE exception here
    if ((P_array[i] > P_array[maxIndex])){
        maxIndex = i;
        System.out.print(new DecimalFormat("#0.00").format(P_array[i]));
         System.out.print(",");
         P_array[maxIndex]= null;   //also getting NPE exception here
         index_sorting[sort_index] = maxIndex;
         sort_index++;
        }
    }
} 

除了用 null 替换元素之外,还有什么更好的方法来完成任务?

【问题讨论】:

  • 您在哪一行得到了异常?
  • 那么,你想要一个索引数组,并让这个数组按照匹配的双精度值的降序排序,对吗?所以 [1.0, 2.0, 0.0] 会给出 [1, 0, 2]?
  • @reek 更新答案...
  • @JB 是的,我想要那样
  • 在将 null 与 double 进行比较时,您可能会得到 npe。

标签: java arrays sorting nullpointerexception


【解决方案1】:

有一种更简单快捷的方法可以做到这一点,是的。只需创建一个索引数组,并根据它们匹配的双精度值对其进行排序:

double[] array = new double[] {2.0, 3.0, 0.0, 1.0};

Integer[] result = new Integer[array.length];
for (int i = 0; i < result.length; i++) {
    result[i] = i;
}
Arrays.sort(result, Comparator.<Integer>comparingDouble(index -> array[index]).reversed());

System.out.println("result = " + Arrays.toString(result));
// [1, 0, 3, 2]

【讨论】:

    【解决方案2】:
        double[] array = new double[] {2.0, 3.0, 0.0, 1.0};
    
        Integer[] result = IntStream.range(0, array.length).boxed().toArray(Integer[]::new);
        Arrays.sort(result, Comparator.<Integer> comparingDouble(i -> array[i]).reversed());
    
        System.out.println(Arrays.toString(result));
    

    【讨论】:

    • 输出:[1, 0, 3, 2]
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2014-11-06
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多