微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

即使条目不为空,也无法访问所有Map.Entry <>元素,在几次迭代后会引发NPE需要知道为什么吗?

如何解决即使条目不为空,也无法访问所有Map.Entry <>元素,在几次迭代后会引发NPE需要知道为什么吗?

  1. 此处出现异常“ wt + = sum-entry.getKey();”

  2. 根据我的说法,代码中发生了什么以及可能的原因。

  3. 使用“ FindMinimum”方法。我试图找到一个满足特定条件的“条目”
    条件。

  4. 找到该条目。我们正在使用“ main”方法从TreeMap中动态删除相应的条目。

  5. 循环继续...

  6. NPE是在到达sMap中最后一个剩余元素时引起的。 [根据我的看法,除非sMap为空,否则不应引起这种情况。]

  7. 可能性为1.)我使用的逻辑错误。 2)可选不是 正确使用。 这类似于OS进程调度问题,最短的作业优先。

    这是一个hackerrank问题。 https://www.hackerrank.com/challenges/minimum-average-waiting-time/problem

    import java.util.*;
    
    public class MinimumAverageWaitingTime {
        private static Map<Integer,Integer> sMap = new TreeMap<>();
        private static int sum = 0,wt = 0;
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(system.in);
            int n = sc.nextInt();
            int[][] mat = new int[n][2];
            for(int i = 0; i < n; i++) {
                mat[i][0] = sc.nextInt();
                mat[i][1] = sc.nextInt();
                sc.nextLine();
            }
            buildTree(mat);
            sum = sMap.keySet().stream().min(Integer::compare).orElse(0);
            for(int j = 0; j < mat.length; j++) {
                Map.Entry<Integer,Integer> entry = findMinimum(sum);
    
                wt += sum - entry.getKey();
                sum += entry.getValue();
                sMap.remove(entry.getKey());
            }
            System.out.println(wt);
        }
        public static void buildTree(int[][] mat) {
            Arrays.stream(mat).forEach(line -> sMap.put(line[0],line[1]));
        }
    
        public static Map.Entry<Integer,Integer> findMinimum(int arrivalTime) {
            if(sMap.size() < 1) {
                return null;
            }
            return sMap
                   .entrySet()
                   .stream()
                   .filter(x -> x.getKey() <= arrivalTime)
                   .min((x,y) -> {
                       System.out.println(x + " " + y);
                       if(x.getValue() > y.getValue()) {
                           return 1;
                       } else if(x.getValue() < y.getValue()) {
                           return -1;
                       } else {
                           return 0;
                       }
                   })
                    .orElse(null);. // This returns null even before the iteration is complete.
        }
    }
    

解决方法

public static Map.Entry<Integer,Integer> findMinimum(int arrivalTime) {
            if(sMap.size() < 1) {
               //System.out.println("null is hit");
                return null;
            }

然后:

wt += sum - entry.getKey();
sum += entry.getValue();

至少在这里您有潜在的NPE

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。