Java集合元素排序技术

package demo;

public class Student implements Comparable//该接口用于排序
{
private int sno;
private String name;
private double score;
public Student(int sno, String name, double score)
{
this.sno = sno;
this.name = name;
this.score = score;
}
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;
}
public int getSno()
{
return sno;
}
public void setSno(int sno)
{
this.sno = sno;
}
//用于排序
public int compareTo(Object obj)
{
Student stu = (Student)obj;
if(this.score < stu.getScore())
{
return 1;
}
else if(this.score > stu.getScore())
{
return -1;
}
else
{
return 0;
}
}
}


package demo;
import java.util.*;
public class ClassT08
{
private ArrayList list;
public ClassT08()
{
list = new ArrayList();
}
public void addStudent(Student student)
{
list.add(student);
}
public void showAllStudents()
{
Collections.sort(list);//先排序后显示
Iterator it = list.iterator();
while(it.hasNext())
{
Student student = (Student)it.next();
System.out.println("ID: "+student.getSno());
System.out.println("Name: "+student.getName());
System.out.println("Score: "+student.getScore());
}
}
public Student findStudent(int sno)
{
Iterator it = list.iterator();
while(it.hasNext())
{
Student student = (Student)it.next();
if(student.getSno() == sno)
{
return student;
}
}
return null;
}
}


package demo;
import javax.swing.*;
public class Test
{
public static void main(String[] args)
{
ClassT08 t08 = new ClassT08();
t08.addStudent(new Student(1,"Jacky",90));
t08.addStudent(new Student(2,"Lucy",95));
t08.addStudent(new Student(3,"Tom",80));
t08.showAllStudents();
int id = Integer.parseInt(JOptionPane.showInputDialog("请输入要查询的学员学号: "));
Student stu = t08.findStudent(id);
if(stu == null)
{
JOptionPane.showMessageDialog(null, "未找到!");
}
else
{
JOptionPane.showMessageDialog(null, stu.getSno() + " " + stu.getName() + " " + stu.getScore());
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值