Reputation: 11
I am having a problem with understanding and using the Comparator I have been asked the following:
Create a CompanyDataBase class.
public java.util.ArrayList sortByName() You'll need to use a Comparator object for this.
I have written this method in the class.
@Override
public int sortByName(Employee name1, Employee name2)
{
return (int) (name1.super.getName() - name2.super.getName());
}
And this seperate Comparator class:
import java.util.*;
public class EmployeeNameComparator implements Comparator<Employee>
{
public int compare(Employee first, Employee second)
{
return (int) (first.super.getName() - second.super.getName());
}
}
But I obviously wont be using the same "return (int) (name1.super.getName() - name2.super.getName());" line of code in both classes...but I have no idea how to implement it in the sortByName method.
I am using a compareTo Comparator interface in a separate Employee class to invoke an overloaded use of the Comparator object.
Any help, suggestions, lines of code would be really appreciated!!
Upvotes: 0
Views: 1104
Reputation: 14286
You are comparing two Strings ... so you can (if they are not null) do this:
name1.compareTo(name2);
Now you need to take nulls into account ... so your comparator would look something like this:
public class EmployeeNameComparator implements Comparator<Employee>
{
public int compare(Employee first, Employee second)
{
if (first != null && second != null) {
if (first.getName() != null) {
return first.getName().compareTo(second.getName());
}
}
.. other cases here
}
}
Upvotes: 0
Reputation: 28568
Strings aren't primitives and can't use subtraction.
Use the Comparable interface of strings to do this work
public int compare(Employee first, Employee second)
{
return first.getName().compareTo(second.getName());
}
Upvotes: 2