java按升序和降序排序自定义对象价格值
我有如下字符串格式的价格值,来自自定义对象
2000,3000,5000300,600,507-
我想按升序和降序对上述价格值进行排序
谁能帮忙吗
我试过:
Comparator<Cars> comparator = new Comparator<Cars>() {
@Override
public int compare(Cars object1, Cars object2) {
// return Float.compare(Integer.parseInt(object1.getPrice()), Integer.parseInt(object2.getPrice()));
String price1=object1.getPrice().replaceAll(",","");
price1=price1.replaceAll("-","");
String price2=object2.getPrice().replaceAll(",","");
price2=price2.replaceAll("-","");
return ((Integer)Integer.parseInt(price1)).compareTo((Integer)Integer.parseInt(price2));
}
};
但是如果我执行这个声明
收藏。排序(carsList、comparator)
获得例外
例外情况:Error:java.lang.NumberFormatException: Invalid int: ""
# 1 楼答案
由于数组中的“-”元素而发生。当你这么做的时候:
新的price1字符串包含一个空字符串“”
导致以下
Integer.parseInt
语句以NumberFormatExcpetion
失败As
parsetInt
无法将空字符串转换为数字所以一种解决方案是要么从数组中移除这样的元素
另一种解决方案是为空字符串定义一个默认值整数。比如: