1)创建一个ArrayList对象list,将上述三位学生加入到集合中,并遍历list,显示学生信息;
2)在学生 “liu”的前面插入一个学生,学生的信息如下:("li",1409,16,"english")并再一次遍历list,确认学生“li”已经被正确插入。
3)根据学生的年龄,按照年龄从小到大的顺序对这4位学生进行排序,并再次遍历,显示学生信息。
package ldz;
import java.util.*;
public class ArrayList1 {
public static void main(String[] args) {
List<Student> c = new ArrayList<Student>();
Student s1=new Student("zhang",1401, 20, "computer");
Student s2=new Student("liu",1402,19,"law");
Student s3=new Student("wang",1403,17,"mechanical");
c.add(s1);
c.add(s2);
c.add(s3);
Iterator<Student> it = c.iterator();
while (it.hasNext()) {
Student s = it.next();
System.out.println(s);
System.out.println();
}
Student s4=new Student("li",1409,16,"english");
c.add(1,s4);
Iterator<Student> it1 = c.iterator();
while (it1.hasNext()) {
Student s = it1.next();
System.out.println(s);
System.out.println();
}
// Collections.sort(c); //11111
// Collections.sort(c,new Outcompare()); //222222
Collections.sort(c,new Comparator<Student>(){
/*@Override
public int compare(Object o1, Object o2) {
Student w1 = (Student)o1;
Student w2 = (Student)o2;
return w1.getAge()-w2.getAge();
}*/
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}});
Iterator<Student> it2 = c.iterator();
while (it2.hasNext()) {
Student s = it2.next();
System.out.println(s);
System.out.println();
}
}
}
package ldz;
import java.util.Comparator;
public class Outcompare implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Student w1 = (Student)o1;
Student w2 = (Student)o2;
return w1.getAge()-w2.getAge();
}
}
package ldz;
public class Student implements Comparable {
private String name;
private int id;
private int age;
private String major;
public Student(String name, int id, int age, String major) {
super();
this.name = name;
this.id = id;
this.age = age;
this.major = major;
}
public int getAge() {
return age;
}
public String toString() {
return "Student [name=" + name + ", id=" + id + ", age=" + age + ", major=" + major + "]";
}
@Override
public int compareTo(Object o) {
Student s = (Student)o;
return this.age-s.getAge();
}
}