Java集合元素排序技术_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java集合元素排序技术

Java集合元素排序技术

 2013/12/12 16:09:18  yangsen2012  程序员俱乐部  我要评论(0)
  • 摘要:packagedemo;publicclassStudentimplementsComparable//该接口用于排序{privateintsno;privateStringname;privatedoublescore;publicStudent(intsno,Stringname,doublescore){this.sno=sno;this.name=name;this.score=score;}publicStringgetName(){returnname;
  • 标签: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());
}
}
}
发表评论
用户名: 匿名