Collections.sort(list, new Comparator<List>(){
//重写排序规则
public int compare(List o1, List o2) {
return 0
}
})
里面那个可以List可以封装成bean,这样就可以在bean里继承Comparator,实现排序方法。一次排序不行可以多次排,关键看你的排序规则要写对。
写那么麻烦干什么呢,看我的!Book[] books = { new Book("j2me",12), new Book("j2se",5), new Book("j2ee",22) }
Arrays.sort (books, new Comparator<Book> ()
{
@Override
public int compare ( Book o1, Book o2 )
{
if (o1.getPrice() > o2.getPrice() )
{
return 1
}
else if (o1.getPrice() < o2.getPrice() )
{
return -1
}
else
{
return 0
}
}
})
import java.util.ArrayListimport java.util.Collections
import java.util.List
public class Test {
public static void main(String[] args) {
List<User> list = new ArrayList<User>()
list.add(new User(11, "Aice", 1))
list.add(new User(11, "john", 2))
list.add(new User(11, "Bob", 3))
list.add(new User(11, "Anni", 4))
Collections.sort(list)
for (User user : list) {
System.out.println(user.name)
}
}
}
class User implements Comparable<User> {
int age
String name
int id
public User() {
}
public User(int age, String name, int id) {
super()
this.age = age
this.name = name
this.id = id
}
@Override
public int compareTo(User o) {
return this.name.compareTo(o.name)
}
}