代码
package com.chen.集合框架和泛型.Collections; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; /** * Created by chen on 2018/3/16. */ public class LearnCollections { public static void main(String[] args) { Student student1 = new Student(1); Student student2 = new Student(2); Student student3 = new Student(3); Student student4 = new Student(4); ArrayList arrayList = new ArrayList(); arrayList.add(student3); arrayList.add(student1); arrayList.add(student4); arrayList.add(student2); System.out.println("----排序前------"); Iterator iterator = arrayList.iterator(); while (iterator.hasNext()){ System.out.println(((Student)iterator.next()).getStudentNo()); } System.out.println("------排序后------"); System.out.println("对list集合中的对象进行排序,前提对象必须实现Comparable接口"); Collections.sort(arrayList); iterator = arrayList.iterator(); while (iterator.hasNext()){ System.out.println(((Student)iterator.next()).getStudentNo()); } System.out.println("-----binarySearch查找student2的索引------"); int index = Collections.binarySearch(arrayList,student2); System.out.println(index); System.out.println("----替换元素-----"); ArrayList list = new ArrayList(); list.add("fill1"); list.add("fill2"); list.add("fill3"); list.add("fill4"); Collections.fill(list,"fill100"); Iterator iterator1 = list.iterator(); while (iterator1.hasNext()){ System.out.println(iterator1.next()); } }
}
package com.chen.集合框架和泛型.Collections; /** * Created by chen on 2018/3/16. */ public class Student implements Comparable { private int studentNo; private String studentName; private String sex; public Student(int studentNo) { this.studentNo = studentNo; } public int getStudentNo() { return studentNo; } public void setStudentNo(int studentNo) { this.studentNo = studentNo; } public Student(String studentName, String sex) { this.studentName = studentName; this.sex = sex; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public int compareTo(Object o) { Student student = (Student) o; if (this.studentNo == student.studentNo) { return 0; } else if (this.studentNo > student.studentNo) { return 1; } else { return -1; } } }
笔记
Collections类是java提供的一个集合操作工具类,它包含了大量的静态方法。 Collections和Collection是不同的,前者是集合的操作类,后者是集合接口。 Collections方法: sort():对集合元素进行排序,java中如果要实现对一个对象比较大小,这个类要实现Comparable接口, 实现int compareTo()方法,然后再用 Collections.sort();进行自动排序。 binarySearch():对集合进行查找 fill():替换集合元素