java-list运用

编写学生类,该类定义了3个属性:学号、姓名、成绩。可以通过构造方法设置3个属性的内容,并覆写Object类中的toString()方法,在List集合中加入5个学生对象,并将内容输出,之后使用比较器将对象的内容进行排序并显示在屏幕上。



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student implements Comparable{
	private int sno;
	private String name;
	private double score;
	public int getSno() {
		return sno;
	}
	public void setSno(int sno) {
		this.sno = sno;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	Student(int _sno,String _name,double _score){
		this.sno=_sno;this.name=_name;this.score=_score;
	}
	public String toString(){
		return "学号:"+sno+"  姓名:"+name+"  分数:"+score;
	}
	public int compareTo(Student s2){
		return (int)(this.getScore()-s2.getScore());
	}
}

public class P7_01 {
	public static void main(String args[]) {
		List list=new ArrayList();
		list.add(new Student(12,"小明",65.5));
		list.add(new Student(13,"小红",70));
		list.add(new Student(14,"小绿",69));
		list.add(new Student(15,"小紫",75));
		list.add(new Student(16,"小白",74));
		Collections.sort(list);
		for(Student s:list){
			System.out.println(s.toString());
		}
	}
}



java-list运用_第1张图片


你可能感兴趣的:(.....java学习)