所以这就是我所困惑的。 在我的主要方法中,我有许多Faculty对象。 除了拥有FacultyList Arraylist。
ArrayList<Faculty> FacultyList = new ArrayList<>();
Faculty faculty1 = new Faculty(fName, "Bob", age, department, position);
Faculty faculty2 = new Faculty(fName, "Anderson", age, department, position);
Faculty faculty3 = new Faculty(fName, "Yvetal", age, department, position);
Faculty faculty4 = new Faculty(fName, "Thompson", age, department, position);
FacultyList.add(faculty1);
FacultyList.add(faculty2);
FacultyList.add(faculty3);
FacultyList.add(faculty4);
现在的情况是我需要创建一个方法或者只是将代码放在主程序中以根据最后的名字进行插入分类。
我之前有这个,它没有改变任何东西。
private static void insertionFaculty(ArrayList<Faculty> array)
{
Faculty temp;
for(int i = 1; i < array.size(); i++)
{
temp = array.get(i);
for(int j = i; j > 0; j--)
{
if(temp.getLastName().compareTo(array.get(j-1).getLastName()) < 0)
{
array.set(j, array.get(j - 1));
}
else
break;
array.set(j, temp);
}
}
}
请帮助:)
答案 0 :(得分:0)
在您的Faculty类中实现可比较,并通过执行以下操作覆盖compareTo方法,
public class Faculty implements Comparable
{
String lastName = .................
.....................
public int compareTo(Object o)
{
Faculty faculty = (Faculty)o;
String olastName = faculty.getLastName();
return lastName.compareTo(olastName);
}
}
然后您需要做的就是在您的FacultyList上调用Arrays.sort,并按姓氏对其进行排序,
Arrays.sort(FacultyList);