程序根据名称对对象进行排序。该程序使用多线程,但是当我使用它时,输出包含列表中第一项的副本。在添加多线程(特别是Runnable)之前,该程序运行良好。在对列表进行排序之后立即发生错误。
这是ClassRank类的一部分,它包含对方法的排序:
public List<Student> nameOrder(List<Student> students)
{
//Keeps sorting until sorted.
boolean notSorted = true;
while (notSorted)
{
//Count keeps track of how many items are in order.
int count = 1;
for (int i = 0; i < students.size() - 1; i++)
{
//nameFront is a name ahead of the nameBehind in the list.
String nameFront = students.get(i).getName();
String nameBehind = students.get(i + 1).getName();
//Determines lexicographical relationship between the names.
if (nameFront.compareToIgnoreCase(nameBehind) > 0 )
{
Student studentFront = students.get(i);
students.set(i, students.get(i + 1));
students.set(i + 1, studentFront);
}
else if (nameFront.compareToIgnoreCase(nameBehind) == 0)
{
double frontWorth = students.get(i).pointValue();
double behindWorth = students.get(i + 1).pointValue();
if(frontWorth < behindWorth)
{
Student studentFront = students.get(i);
students.set(i, students.get(i + 1));
students.set(i + 1, studentFront);
}
}
else
{
count++;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count == students.size())
{
notSorted = false;
}
}
return students;
}
这是主要方法:
List<Student> list1 = new ArrayList<Student>();
//students is the list made from extracting the data file with
//the objects
for(Student student: students)
{
list1.add(student);
}
ClassRank listNames = new ClassRank();
Thread name = new Thread(new Runnable()
{
public void run()
{
//Command to sort students alphabetically
listNames.nameOrder(list1);
}
});
name.start();
for (Student i : list1)
{
System.out.println(i.toString());
}
System.out.println();
这是排序列表的输出
Matthew Diaz 3.6 1420 3
Carl Baab 1.6 750 2
Connor Morgan 3.2 1260 3
Daniel Deyoung 2.8 460 3
David Navas 2.9 1450 1
Dominic Mazza 3.9 1460 3
Ethan Gieger 3.5 1310 3
George Scaglione 3.5 1300 1
Hayle Short 3.8 1410 7
Jake Orlick 4.0 1340 5
Joshua Saunders 3.5 1510 7
Matthew Diaz 3.6 1420 3
Robert Dick 3.8 1460 2
Samuel Rodriguez 3.8 1360 3