我想对包含时区值的字符串值进行排序,以实现可比较接口。
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class TimeZoneModel implements Comparable {
private Integer id;
private String value;
public int getId() {
return id;
}
public String getValue() {
return value;
}
public void setId(Integer id) {
this.id = id;
}
public void setValue(String value) {
value = value;
}
public TimeZoneModel(String value){
this.value= value;
}
public int compareTo(Object object) {
TimeZoneModel timezoneModel= null;
if(object instanceof TimeZoneModel){
timezoneModel=(TimeZoneModel)object;
}
return /*value.compareTo*/((timezoneModel.getValue()!=null?timezoneModel.getValue():"")).compareTo(value);
}
public static void main(String args[]){
TimeZoneModel timezoneModel = new TimeZoneModel("+01:00");
TimeZoneModel timezoneModel1 = new TimeZoneModel("+02:30");
TimeZoneModel timezoneModel2 = new TimeZoneModel("-01:00");
TimeZoneModel timezoneModel3 = new TimeZoneModel("-11:00");
TimeZoneModel timezoneModel4 = new TimeZoneModel("+05:00");
List<TimeZoneModel> timeZoneModelList = new ArrayList<TimeZoneModel>();
timeZoneModelList.add(timezoneModel);
timeZoneModelList.add(timezoneModel1);
timeZoneModelList.add(timezoneModel2);
timeZoneModelList.add(timezoneModel3);
timeZoneModelList.add(timezoneModel4);
Collections.sort(timeZoneModelList);
for(TimeZoneModel timezoneModelw : timeZoneModelList){
System.out.println(timezoneModelw.getValue());
}
}
}
在上面的程序中,我想基于值进行自定义排序。我为此使用了可比的接口。
我得到的输出:
-11:00
-01:00
+05:00
+02:30
+01:00
预期的输出是:
-11:00
-01:00
+01:00
+02:30
+05:00
我想跳过字符串到整数的转换。整数对话对我来说是最后的选择。
使用以下版本的compareTo
方法
@Override
public int compareTo(Object object) {
TimeZoneModel timezoneModel = null;
Double val1 = 0d;
Double val2 = 0d;
if (object instanceof TimeZoneModel) {
timezoneModel = (TimeZoneModel) object;
String strVal = timezoneModel.getValue();
if (strVal != null) {
strVal = strVal.replace(":", ".");
if (strVal.contains("-")) {
val1 = Double.valueOf(strVal.replace("-", ""));
val1 = val1 * -1;
} else {
val1 = Double.valueOf(strVal.replace("+", ""));
}
}
String value = this.value.replace(":", ".");
if (value.contains("-")) {
val2 = Double.valueOf(value.replace("-", ""));
val2 = val2 * -1;
} else {
val2 = Double.valueOf(value.replace("+", ""));
}
}
return val2.compareTo(val1);
}
我所做的是为了进行比较,我将String值转换为Double
而不丢失sign
和minutes
值。我已经使用String.replace
了相同的方法。(即用于删除+ - :
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句