我想根据成员的值对A
类的对象进行排序:a
,b
,c
:A
被给予最多偏好 - > b
是下一个 - > c
最不喜欢。
比较器用于:
x = x.sortWith(comparator)
这里,x是一个ArrayBuffer [A]
class A {var a,b,c = 0}
def comparator(f1:A, f2:A) = {
if(f1.a == f2.a) {
if(f1.b == f2.b) f1.c > f2.c
else f1.b > f2.b
}
else f1.a > f2.a
}
使用这个我得到:
**java.lang.IllegalArgumentException: Comparison method violates its general contract!**
at java.util.TimSort.mergeLo(TimSort.java:747)
at java.util.TimSort.mergeAt(TimSort.java:483)
at java.util.TimSort.mergeCollapse(TimSort.java:410)
at java.util.TimSort.sort(TimSort.java:214)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at scala.collection.SeqLike$class.sorted(SeqLike.scala:618)
at scala.collection.AbstractSeq.sorted(Seq.scala:41)
at scala.collection.SeqLike$class.sortWith(SeqLike.scala:575)
at scala.collection.AbstractSeq.sortWith(Seq.scala:41)
答案 0 :(得分:1)
使用sortBy
和元组:
x sortBy {f => (f.a, f.b, f.c)}
答案 1 :(得分:0)
您能提供更全面的测试用例吗?这个例子适合我:
class A {var a,b,c = 0}
def comparator(f1:A, f2:A) = {
if(f1.a == f2.a) {
if(f1.b == f2.b) f1.c > f2.c
else f1.b > f2.b
}
else f1.a > f2.a
}
val testList = new scala.collection.mutable.ArrayBuffer[A]
val val1 = new A()
val val2 = new A()
val val3 = new A()
val1.a=1
val1.b=1
val1.c=1
val2.a = 1
val2.b = 1
val2.c = 1
val3.a = 2
val3.b = 2
val3.c = 3
testList += val1
testList += val2
testList += val3
testList.sortWith(comparator)