我想在java中有一个排序的集合,我可以迭代它。从我读到的 PriorityQueue 是我需要的东西,但是我无法弄清楚如何以排序方式检索元素......
我做了这个测试示例:
主.java
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Object> queue=new PriorityQueue<Object>();
Object o1=new Class1("o1");
Object o2=new Class2("o2");
Object o3=new Class1("o3");
Object o4=new Class1("o4");
Object o5=new Class2("o5");
Object o6=new Class2("o6");
Object o7=new Class1("o7");
Object o8=new Class2("o8");
Object o9=new Class1("o9");
Object o0=new Class1("o0");
queue.add(o7);
queue.add(o4);
queue.add(o3);
queue.add(o8);
queue.add(o5);
queue.add(o1);
queue.add(o2);
queue.add(o9);
queue.add(o0);
queue.add(o6);
for (Object object : queue) {
System.out.println(object);
}
}
}
类1.java:
public class Class1 implements Comparable<Object>{
String name;
public Class1(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Class1 [name=" + name + "]";
}
@Override
public int compareTo(Object o) {
return (o instanceof Class1)?compareTo((Class1)o):compareTo((Class2)o);
}
public int compareTo(Class1 o){
return name.compareTo(o.name);
}
public int compareTo(Class2 o){
return name.compareTo(o.name2);
}
}
类2.java:
public class Class2 implements Comparable<Object>{
String name2;
public Class2(String name) {
super();
this.name2 = name;
}
@Override
public String toString() {
return "Class2 [name=" + name2 + "]";
}
@Override
public int compareTo(Object o) {
return (o instanceof Class1)?compareTo((Class1)o):compareTo((Class2)o);
}
public int compareTo(Class1 o){
return name2.compareTo(o.name);
}
public int compareTo(Class2 o){
return name2.compareTo(o.name2);
}
}
这将返回:
Class1 [name=o0]
Class1 [name=o1]
Class2 [name=o2]
Class2 [name=o5]
Class2 [name=o6]
Class1 [name=o4]
Class1 [name=o3]
Class1 [name=o9]
Class2 [name=o8]
Class1 [name=o7]
我需要做什么才能以排序方式迭代此集合?