「java」java.util.Collections.sort()の使い方

1.インタフェース
package com.changfa;
public class User implements Comparable<User>{
private String name;
private Integer order;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public int compareTo(User arg0) {
return this.getOrder().compareTo(arg0.getOrder());
}
}

 

2.Javaコード
package com.changfa;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestInter {

public static void main(String[] args) {

User user1 = new User();
user1.setName(“yamada");
user1.setOrder(1);
User user2 = new User();
user2.setName(“aso");
user2.setOrder(2);
List<User> list = new ArrayList<User>();
//要素追加
list.add(user2);
list.add(user1);
Collections.sort(list);
for(User u : list){
System.out.println(u.getName());
}

}

}

3.実行結果
yamada
aso

Java

Posted by arkgame