#、在一个列表中存储以下元素:apple,grape,banana,pear
3.1 返回集合中的最大的和最小的元素
3.2 将集合进行排序,并将排序后的结果打印在控制台上 [必做题]
public class T1fruits implements Comparable<T1fruits> {
private String name;
public T1fruits() {
super();
}
public T1fruits(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "T1fruits [name=" + name + "]";
}
@Override
public int compareTo(T1fruits o) {
return this.name.compareTo(o.name);
}
}
public class T1NameComparator implements Comparator<T1fruits> {
@Override
public int compare(T1fruits o1, T1fruits o2) {
return o1.getName().compareTo(o2.getName());
}
}
import java.util.ArrayList;
import java.util.Collections;
public class T1test {
// 在一个列表中存储以下元素:apple,grape,banana,pear
// 3.1 返回集合中的最大的和最小的元素
// 3.2 将集合进行排序,并将排序后的结果打印在控制台上 [必做题]
public static void main(String[] args) {
T1fruits apple = new T1fruits("apple");
T1fruits grape = new T1fruits("grape");
T1fruits banana = new T1fruits("banana");
T1fruits pear = new T1fruits("pear");
ArrayList<T1fruits> list = new ArrayList<>();
list.add(apple);
list.add(grape);
list.add(banana);
list.add(pear);
System.out.println("集合中的元素:"+list);
T1fruits max = Collections.max(list,new T1NameComparator());//以名字比较最大
System.out.println("集合中最大的元素:"+max);
T1fruits min = Collections.min(list,new T1NameComparator());//以名字比较最小
System.out.println("集合中最小的元素:"+min);
Collections.sort(list, new T1NameComparator());//从小到大排序的元素
System.out.println("集合从小到大排序的元素:"+list);
}
}