java - 需要对代码进行哪些更改才能阻止输出包含重复对象
问题描述
该程序根据对象的名称对对象进行排序。该程序使用多线程,但是当我使用它时,输出包含列表中第一项的副本。在添加多线程(特别是 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;
}
这是在 main 方法内部:
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
解决方案
推荐阅读
- javascript - 标签中的自动转发 Gmail 不会转发完整的对话
- c# - 单击图钉/标记时在地图上添加按钮(xamarin 形式)
- powershell - 如果使用电源脚本存在,如何复制和覆盖其中的现有文件夹和文件
- android - 发生IDE致命错误字符串索引超出范围android studio
- c++ - 最大元素的打印索引
- javascript - 如何使用 ajax 帖子和数据表附加数据不起作用?
- r - 双for循环的高效实现
- angular - 为什么角生产构建中的 polyfills 的行为与开发模式中的不同?
- reactjs - 在 React 中更改 Chart.js 的语言环境
- rest - Google 对话流 REST API 超时