[英]What's alternative NSSortDescriptor in Java?
I hava ArrayList which is include Custom Data Class. 我有ArrayList,其中包含自定义数据类。
ArrayList<MyData> list
Custom Data class has several field 自定义数据类有几个字段
class MyData {
private int num;
private String name;
etc....
getter/setter...
}
I want to sort List by field (ex:num) 我想按字段对列表进行排序(例如:num)
Objecitive-C has NSSortDescriptor which can sort objects. Objecitive-C具有可以对对象进行排序的NSSortDescriptor。
NSSortDescriptor Class Reference NSSortDescriptor类参考
is There alternative this? 还有其他选择吗? or other solution? 或其他解决方案?
You can use Comparable and Comparator interface.. and the use Collection.sort(). 您可以使用Comparable和Comparator接口..并使用Collection.sort()。
You need to implement Comparable and Comparator interface, if you are using Collection of Custom Type(ie not primitive types). 如果使用自定义类型的集合(即不是原始类型),则需要实现Comparable和Comparator接口。
For detailed examples check http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ 有关详细示例,请访问http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
Hope this post will be helpful to u. 希望这篇文章对您有所帮助。
java.util.Comparator coupled with java.util.Collection.sort should do the trick. java.util.Comparator与java.util.Collection.sort一起应该可以解决问题。
You could also have MyData
implement java.util.Comparable and use the other sort method, but that isn't quite as flexible. 您也可以让MyData
实现java.util.Comparable并使用其他sort方法,但这并不那么灵活。
There is nothing similar to NSSortDescriptor
in Java: Java sorting uses the style that is more similar to the sortUsingComparator:
method of the NSMutableArray
class: Java中没有与NSSortDescriptor
类似的NSSortDescriptor
:Java排序使用的样式与NSMutableArray
类的sortUsingComparator:
方法更相似:
Collections.sort(list, new Comparator<MyData>() {
// This is similar to the comparator block of Cocoa
public int compare(MyData o1, MyData o2) {
// Put the comparison code here
...
}
});
Implement Comparable or Comparator and use Collections.sort() . 实现Comparable或Comparator并使用Collections.sort() 。
public class MyClass implements Comparable<MyClass>{
public int x;
public int compareTo(MyClass mc){
return x - mc.x;
}
}
public class MyClass{
public int x;
}
public class MyClassComparator implements Comparator<MyClass>{
public int compare(MyClass mc1, MyClass mc2){
return mc1.x - mc2.x;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.