题目:在一个列表中存储以下元素:apple,grape,banana,pear,现要求将集合进行排序,返回集合中的最大的和最小的元素,并将排序后的结果打印在控制台上,要求的打印输出方法分别为默认toString输出、迭代器输出、for循环遍历输出和增强for循环输出。
package test;
import java.util.*;
public class Pratice3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("grape");
list.add("banana");
list.add("pear");
Collections.sort(list,new Comparator<String>(){
@Override
public int compare(String arg0, String arg1) {
// TODO Auto-generated method stub
return arg0.compareTo(arg1);
}
});
System.out.println("最大元素:"+list.get(list.size()-1));
System.out.println("最小元素:"+list.get(0));
System.out.println("***默认toString输出***");
System.out.println(list);
System.out.println("***迭代器遍历输出***");
Iterator<String> it = list.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println("***for循环遍历输出***");
for(int i = 0;i<list.size();i++){
System.out.print(list.get(i)+" ");
}
System.out.println();
System.out.println("***增强for循环输出***");
for(String i :list){
System.out.print(i+" ");
}
}
}
输出:
最大元素:pear
最小元素:apple
***默认toString输出***
[apple, banana, grape, pear]
***迭代器遍历输出***
apple banana grape pear
***for循环遍历输出***
apple banana grape pear
***增强for循环输出***
apple banana grape pear