Gordon Igor
Gordon Igor

Reputation: 35

Collection sort of list contains 2 objects

I have a list, which contains 2 objects of type Departments and Managers.

I need to sort the list alphabetically by Departments. The Department class implements Comparable<Department> and has the method compareTo. But I receive an error message:

"The method sort(List, Comparator) in the type Collections is not applicable for the arguments (List, new Comparator(){})"

public static List<?> getLst(String fileName)throws FileNotFoundException, IOException,ClassNotFoundException {
    List<Object> lst = new LinkedList<>();
    BufferedInputStream f;
    try(ObjectInputStream i = new ObjectInputStream(f=new BufferedInputStream(new FileInputStream(fileName)))){
        while (f.available()>0) {
            lst.add(i.readObject());
        }

        Collections.sort(lst, new Comparator<Department>() {
              @Override
              public int compare(Department object1,Department object2) {
                  return object1.getDepName().compareTo(object2.getDepName());
              }
          });
    }
    return lst;
} 

Upvotes: 1

Views: 124

Answers (2)

user3458
user3458

Reputation:

The design that puts managers an departments in the same list sounds suspect. Are you making a model for a Tree widget? There are better ways for that ...

In any case, you can do one of two things:

  • provide Comaparator and cast inside as needed (bad idea)
  • or have both Department and Manager implement HasDepartment with getDepartment() method, and build your Comparator for that.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140447

You are not using generics correctly.

Collections.sort() wants:

  • a List<T> and
  • a matching Comparator<T>

You are providing a List of Objects; but a Comparator of Departments. That simply can't work.

So, one way of resolving this - first change your list to use the proper generic type:

List<Department> departments = new ArrayList<>();

and later ... add the (now necessary) cast so that the incoming "Object" can be added to that list of departments - if it has the correct type!

 Object fromStream = i.readObject();
 if (fromStream instanceof Department) {
    departments.add( (Department) fromStream);
 } else {
   // consider what to do with managers objects ...

( please note: lst is a bad name; it says nothing, and that one saved character only adds confusion. Use names that express what the thing behind is about; like departments to make clear: something that contains, well departments in plural )

Update: the generics give a hint that you have a design problem here. If you want to sort departments, then your list containing departments should not contain anything else.

In other words: the real answer here is to not use one list that contains different types of objects, but to use two lists instead.

Upvotes: 4

Related Questions