2018.12.18 java22

假设顺序列表ArrayList中存储的元素是整型数字1~5,遍历每个元素,将每个元素顺序输出

public static void main(String[] args) { ArrayList arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(4); arr.add(5); arr.add(3); for(Object obj:arr) {System.out.println(obj.toString()); }System.out.println(arr);

3、在一个列表中存储以下元素:apple,grape,banana,pear
【2018.12.18 java22】3.1 返回集合中的最大的和最小的元素
3.2 将集合进行排序,并将排序后的结果打印在控制台上
public class Fruit implements Comparable{ private String name; public Fruit() { super(); // TODO 自动生成的构造函数存根 } @Override public String toString() { return "Fruit [name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Fruit other = (Fruit) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Fruit(String name) { super(); this.name = name; } @Override public int compareTo(Fruit arg0) { // TODO 自动生成的方法存根 return this.name.compareTo(arg0.name); } }public static void main(String[] args) { Fruit fru1 = new Fruit("apple"); Fruit fru2 = new Fruit("grape"); Fruit fru3 = new Fruit("banana"); Fruit fru4 = new Fruit("pear"); ArrayList list = new ArrayList<>(); list.add(fru1); list.add(fru2); list.add(fru3); list.add(fru4); Fruit max = Collections.max(list); System.out.println("Max="+max); Fruit min = Collections.min(list); System.out.println("Min="+min); Collections.sort(list); System.out.println(list);

从控制台输入若干个单词(输入回车结束)放入集合中,将这些单词排序后(忽略大小写)打印出来
ArrayList> list = new ArrayList<>(); Scanner in = new Scanner(System.in); String s = in.nextLine(); String[] a = s.split(" "); for(int i=0; i < a.length; i++){ for(int j =i+1; j0){ s = a[i]; a[i]= a[j]; a[j] = s; } } } for(String o:a){ list.add(o); System.out.println(o); } System.out.println(list);

    推荐阅读