蛮力方式:
public final class ColorComparator implements Comparator {
@Override
public int compare(Color c1, Color c2) {
float[] hsb1 = Color.RGBtoHSB(c1.getRed(), c1.getGreen(), c1.getBlue(), null);
float[] hsb2 = Color.RGBtoHSB(c2.getRed(), c2.getGreen(), c2.getBlue(), null);
if (hsb1[0] < hsb2[0])
return -1;
if (hsb1[0] > hsb2[0])
return 1;
if (hsb1[1] < hsb2[1])
return -1;
if (hsb1[1] > hsb2[1])
return 1;
if (hsb1[2] < hsb2[2])
return -1;
if (hsb1[2] > hsb2[2])
return 1;
return 0;
}
}
一个非常简单的,没有想到办法做到这一点,如果你可以使用谷歌番石榴库为:
public final class ColorComparator extends Ordering {
@Override
public int compare(Color c1, Color c2) {
float[] hsb1 = Color.RGBtoHSB(c1.getRed(), c1.getGreen(), c1.getBlue(), null);
float[] hsb2 = Color.RGBtoHSB(c2.getRed(), c2.getGreen(), c2.getBlue(), null);
return ComparisonChain.start().compare(hsb1[0], hsb2[0]).compare(hsb1[1], hsb2[1])
.compare(hsb1[2], hsb2[2]).result();
}
}
我在说的只是环数组并对它们进行比较(或者使用Guava中的词典排序),但是您可能想要改变排序顺序。