gpt4 book ai didi

java - Java排序List时出现错误 "no suitable method found"

转载 作者:行者123 更新时间:2023-12-01 22:45:00 27 4
gpt4 key购买 nike

我正在尝试在转换 StringList 后对 IntegerList 进行排序转换为Integer List。它给了我这个错误:

no suitable method found for sort(List,StringToInteger.CustomComparator)

这是我的代码:

public class StringToInteger {

public static void main(String args) {
List<String> strList = new ArrayList<String>();
strList.add("34");
strList.add("14");
strList.add("42");
strList.add("24");

List<String> resultList = getIntegerArray(strList);
System.out.println("before sorting"+resultList);
Collections.sort(resultList, new CustomComparator());
System.out.println("after sorting"+resultList);
}

private static List<Integer> getIntegerArray(List<String> stringArray) {
List<Integer> result = new ArrayList<Integer>();
for(String stringValue : stringArray) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(stringValue));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
}
}
return result;
}

class CustomComparator implements Comparator<List<Integer>> {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(1).compareTo(o2.get(1));
}
}
}

最佳答案

您正在比较 CustomComperator 中的整数列表,而您应该比较整数。您还可以使用

对列表进行排序
Collections.sort(resultList);

Collections.reverse(resultList);

关于java - Java排序List时出现错误 "no suitable method found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501644/

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