gpt4 book ai didi

java - 字符串值时区排序

转载 作者:行者123 更新时间:2023-12-02 03:09:14 25 4
gpt4 key购买 nike

我想对包含时区值的字符串值进行排序,以实现 Comparable 接口(interface)。

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);
}

我所做的是为了进行比较,我将字符串值转换为Double,而不会丢失sign分钟值。我已经使用了 String.replace 方法来实现相同的目的。 (即删除 + - :)

关于java - 字符串值时区排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41298422/

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