【发布时间】:2022-01-01 20:33:56
【问题描述】:
尝试按升序对数组 0f 日志版本进行排序。我可以通过直接将 Comparator 实现为来使其工作
Arrays.sort(input, new CustomComparator())
并在 CustomComparator 类中编写与以下代码(来自 Parse 类)相同的逻辑。但是,当我尝试通过在队列中添加值对其进行排序时,排序不起作用。
import java.util.*;
public class LogSorting {
public static void main(String[] args) {
String[] input = {"2.10.0", "1.0.100", "1.0.1", "1.1.100", "2.1.10", "1.1.1"};
PriorityQueue<Parse> str = new PriorityQueue<>();
for (String i : input) {
String[] result = i.split("\\.");
str.add(new Parse(Integer.parseInt(result[0]), Integer.parseInt(result[1]), Integer.parseInt(result[2])));
}
for (Parse p : str) {
System.out.println(p.major + " " + p.minor + " " + p.patch);
}
}
}
class Parse implements Comparable<Parse> {
int major;
int minor;
int patch;
Parse(int major, int minor, int patch) {
this.major = major;
this.minor = minor;
this.patch = patch;
}
public int compareTo(Parse p) {
if (major == p.major && minor == p.minor)
return Integer.compare(patch, p.patch);
if (major == p.major)
return Integer.compare(minor, p.minor);
return Integer.compare(major, p.major);
}
}
输出
1 0 1
1 1 100
1 0 100
2 10 0
2 1 10
1 1 1
输出应排序为 1 0 1, 1 0 100, 1 1 1, 1 1 100, 2 1 10, 2 10 0
【问题讨论】:
标签: java sorting comparator comparable custom-sort