背景: 我创建了这个员工记录应用程序,您可以在其中添加人员ID,名字,姓氏,薪资和开始日期。它由“添加”按钮,“删除”按钮,“列表”组合框和输出组成。
我需要帮助的是按ID排序arrayList并在输出中显示排序的版本。 `public class EmployeeRecordsView扩展了FrameView {
ArrayList <one> myList = new ArrayList <one>();
//List<one> records = new ArrayList<one>();
String iD, first, last, salary, startDate;
public EmployeeRecordsView(SingleFrameApplication app) {
//Cut out code
}
class one {
String iD, first, last, salary, startDate;
one (String _iD, String _first, String _last, String _salary, String
_startDate){
iD = _iD;
first = _first;
last = _last;
salary = _salary;
startDate = _startDate;
}
}
private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {
one emp;
iD = id.getText();
first = firstName.getText();
last = lastName.getText();
salary = sal.getText();
startDate = start.getText();
emp = new one(iD, first, last, salary, startDate);
myList.add(emp);
}
private void btnRemoveMouseClicked(java.awt.event.MouseEvent evt) {
String remove;
remove = id.getText();
myList.remove(remove);
}
private void btnExitMouseClicked(java.awt.event.MouseEvent evt) {
System.exit(0);
}
private void jComboBox1MouseClicked(java.awt.event.MouseEvent evt) {
if (jComboBox1.getSelectedItem() == "Order of Addition"){
String temp="";
for (int x=0; x<=myList.size()-1; x++) {
temp = temp + "ID#: " + myList.get(x).iD + ", "
+ "First Name: " + myList.get(x).first + ", "
+ "Last Name: " + myList.get(x).last + ", "
+ "Annual Salary: " + myList.get(x).salary + ", "
+ "Starting Date: " + myList.get(x).startDate + "\n";
}
outPut.setText(temp);
}
if (jComboBox1.getSelectedItem() == "ID"){
String temp="";
for (int x=0; x<=myList.size()-1; x++) {
temp = temp + "ID#: " + myList.get(x).iD + ", "
+ "First Name: " + myList.get(x).first + ", "
+ "Last Name: " + myList.get(x).last + ", "
+ "Annual Salary: " + myList.get(x).salary + ", "
+ "Starting Date: " + myList.get(x).startDate + "\n";
}
outPut.setText(temp);
}`
}
答案 0 :(得分:2)
使用Collections.sort(List, Comparator)
,您可以使用List
以自定义方式对Comparator
进行排序。
因此,基于对您one
类的轻微修改,包含一个getter来检索iD
值
class One {
String iD, first, last, salary, startDate;
One(String _iD, String _first, String _last, String _salary, String _startDate) {
iD = _iD;
first = _first;
last = _last;
salary = _salary;
startDate = _startDate;
}
public String getID() {
return iD;
}
}
你可以使用......
Collections.sort(myList, new Comparator<One>() {
@Override
public int compare(One o1, One o2) {
return o1.getID().compareTo(o2.getID());
}
});
现在请注意,这会按照自然顺序对ID进行排序,1
将不会出现在10
之前,这就是String
排序的工作方式...... < / p>