1

So here's what I'm confused about. In my main method I have a a multitude of Faculty objects. In addition to having a 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);

The situation now is that I need to either create a method or just put code in the main program to do an INSERTION SORT BASED ON THE LAST NAMES.

I had this before and it didn't change anything.

   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);
          }
      }
   }

Please help :)

Maximus
  • 11
  • 2
  • Check [this](http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/). You need to implement `comparable` and `comparator` in your `Faculty` class, and then you can use `Collections.sort()` on your `ArrayList`. – Jonas Czech Apr 26 '15 at 20:19
  • I saw this too, but I need to make an insertion sort method or just a block of code, not an inherited code – Maximus Apr 26 '15 at 21:42
  • [This](http://stackoverflow.com/a/8938297/4428462) may help if you want to do it manually. Should work for ArrayList with some changes. – Jonas Czech Apr 27 '15 at 07:05

1 Answers1

0

Implement comparable in your Faculty class and override the compareTo method by doing the following,

 public class Faculty implements Comparable
 {
  String lastName = .................

  .....................


  public int compareTo(Object o)
  {
    Faculty  faculty = (Faculty)o;
    String  olastName = faculty.getLastName();

    return lastName.compareTo(olastName);
  }
 }

then all you need to do is call Arrays.sort on your FacultyList and that should sort it by last name,

Arrays.sort(FacultyList);
faljbour
  • 1,367
  • 2
  • 8
  • 15