好的,这给你。您可以从测试主类运行两个独立的示例解决方案。第一个使用多维数组。
Object values[][] = new Object[][] {
{ "a", Boolean.FALSE },
{ "b", Boolean.TRUE },
{ "c", Boolean.TRUE },
};
Arrays.sort(values,
new Comparator<Object[]>() {
@Override
public int compare(Object[] tuple1, Object[] tuple2) {
int result = -1*((Boolean) tuple1[1]).compareTo((Boolean) tuple2[1]);
if (result == 0) {
result = ((String) tuple1[0]).compareTo(((String) tuple2[0]));
}
return result;
}
}
);
for (Object[] tuple : values) {
System.out.println(Arrays.toString(tuple));
}
第二个使用通用(和类型安全)元组。
class Tuple<A, B> {
private final A first;
private final B second;
public Tuple(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return this.first;
}
public B getSecond() {
return this.second;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "[first=" + first.toString() + ",second=" + second.toString() + "]";
}
};
Tuple<String, Boolean> values[] = new Tuple[] {
new Tuple<String, Boolean>("a", Boolean.FALSE),
new Tuple<String, Boolean>("b", Boolean.TRUE),
new Tuple<String, Boolean>("c", Boolean.TRUE),
};
Arrays.sort(values,
new Comparator<Tuple<String, Boolean>>() {
@Override
public int compare(Tuple<String, Boolean> tuple1, Tuple<String, Boolean> tuple2) {
int result = -1*tuple1.getSecond().compareTo(tuple2.getSecond());
if (result == 0) {
result = tuple1.getFirst().compareTo(tuple2.getFirst());
}
return result;
}
}
);
for (Tuple<String, Boolean> tuple : values) {
System.out.println(tuple);
}