gpt4 book ai didi

java - 基于枚举的排序具有随机行为

转载 作者:行者123 更新时间:2023-11-29 07:29:25 25 4
gpt4 key购买 nike

对于下面的代码,我试图根据枚举类型对 bean 进行排序。此 bean 的枚举类型也可以为 null。

排序后的顺序应该是:

A -> B -> C -> null.

运行下面的代码后,元素排序如下:

[A, A, C, B, B, null, C, null]

请帮忙

public class Bean implements Comparable<Bean> {

enum Type {
A, B, C
}

private Type type;
private int i;
private int j;

public Bean(Type type, int i, int j) {
this.type = type;
this.i = i;
this.j = j;
}

@Override
public int compareTo(Bean that) {
if (this.type == that.type) {
return 0;
}
if (this.type != null && that.type != null) {
if (this.type == type.A &&
that.type == type.B) {
return -1;
}
if (this.type == type.B &&
that.type == type.C) {
return -1;
}
if (this.type == type.A &&
that.type == type.C) {
return -1;
}
return 1;
}

return this.type == null ? 1 : -1;
}

@Override
public String toString() {
return "Bean{" + "type=" + (type != null ? type : "Unknown") + "}";
}

public static void main(String[] args) {
Bean b1 = new Bean(Type.B, 1, 1);
Bean b3 = new Bean(null, 3, 3);
Bean b2 = new Bean(Type.C, 2, 2);
Bean b0 = new Bean(Type.A, 0, 0);
Bean b4 = new Bean(Type.B, 4, 4);
Bean b5 = new Bean(null, 5, 5);
Bean b6 = new Bean(Type.C, 6, 6);
Bean b7 = new Bean(Type.A, 7, 7);

List<Bean> list = new ArrayList<>();
list.add(b1);
list.add(b3);
list.add(b2);
list.add(b0);
list.add(b4);
list.add(b5);
list.add(b6);
list.add(b7);

System.out.println(list);

System.out.println(new PriorityQueue<Bean>(list));
}
}

最佳答案

你应该这样做,而不是打破自己的脖子使枚举无效:

enum Type {
A, B, C, INVALID
}

然后

public Bean(Type type, int i, int j) {
this.type = type == null ? Type.INVALID : type;
this.i = i;
this.j = j;
}

比较器将简单易读:

@Override
public int compareTo(Bean that) {
return this.type.compareTo(that.type);
}

注意这是可能的,因为 Enum<E>工具 Comparable<E>通过枚举的自然顺序

这样做

System.out.println(list);
Collections.sort(list);
System.out.println(list);

将产生:

[Bean{type=B}, Bean{type=INVALID}, Bean{type=C}, Bean{type=A}, Bean{type=B}, Bean{type=INVALID}, Bean{type=C}, Bean{type=A}]
[Bean{type=A}, Bean{type=A}, Bean{type=B}, Bean{type=B}, Bean{type=C}, Bean{type=C}, Bean{type=INVALID}, Bean{type=INVALID}]

关于java - 基于枚举的排序具有随机行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45102553/

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