gpt4 book ai didi

Java比较器使用非final变量

转载 作者:行者123 更新时间:2023-12-03 21:44:47 26 4
gpt4 key购买 nike

我想使用包含每个项目值的映射对列表进行排序。

Map<Integer, Float> map = new HashMap<>();
List<Integer> list = new ArrayList<>();

map.put(0, 0.0f);
map.put(1, 5.0f);
map.put(2, 2.0f);

list = new ArrayList<>(map.keySet());

Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer left, Integer right) {
Float leftCost = map.get(left);
Float rightCost = map.get(right);
return leftCost.compareTo(rightCost);
}
})

我希望顺序为 0,2,1 因为 1 的值高于 2。但是java不让我这样做。我收到以下错误:无法引用在不同方法中定义的内部类中的非最终变量映射

我怎样才能这样做呢?

最佳答案

让它成为最终的:

final Map<Integer, Float> map = new HashMap<Integer, Float>();
List<Integer> list = new ArrayList<Integer>(); // this assignment is unncessary [1]

map.put(0, 0.0f);
map.put(1, 5.0f);
map.put(2, 2.0f);

list = new ArrayList<Integer>(map.keySet()); // 1. assignment is replaced here

Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer left, Integer right) {
Float leftCost = map.get(left);
Float rightCost = map.get(right);
return leftCost.compareTo(rightCost);
}
})

由于您的 map 是可变的,您仍然可以修改它。

关于Java比较器使用非final变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12727299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com