ArrayList存放学生对象及排序
【问题描述】
编写一个学生类,包含姓名、学号、年龄、专业四个属性,并完善get /set方法、构造方法、toString()方法。
toString()方法参考如下:
public String toString() {
return "Student [name=" + name + ", id=" + id + ", age=" + age + ", major=" + major + "]";
}
有三位学生的信息,参考代码如下
Student s1=new Student("zhang",1401, 20, "computer");
Student s2=new Student("liu",1402,19,"law");
Student s3=new Student("wang",1403,17,"mechanical");
请完成以下内容:
1)创建一个ArrayList对象list,将上述三位学生加入到集合中,并遍历list,显示学生信息;
2)在学生 “liu”的前面插入一个学生,学生的信息如下:("li",1409,16,"english")
并再一次遍历list,确认学生“li”已经被正确插入。
3)根据学生的年龄,按照年龄从小到大的顺序对这4位学生进行排序,并再次遍历,显示学生信息。
package test;
//自定义排序
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();
}
}
package test;
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遍历
// while (it.hasNext()) {
// Student s = it.next();
// System.out.println(s);
// System.out.println();
// }
for(Iterator<Student> iter = c.iterator();iter.hasNext();){
Student s = iter.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); //第一种排序内比较
// Collections.sort(c,new Outcompare()); //第二种排序自定义比较器(外)
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 test;
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();
}
}
网友评论