开发者

Passing a comparator syntax help in Java

开发者 https://www.devze.com 2022-12-30 14:53 出处:网络
I\'ve tried this a couple ways, the first is have a class that implements comparator at the bottom of the following code.When I try to pass the comparat in sortListByLastName, I get a constructor not

I've tried this a couple ways, the first is have a class that implements comparator at the bottom of the following code. When I try to pass the comparat in sortListByLastName, I get a constructor not found error and I am not sure why

import java.util.*;

public class OrganizeThis implements WhoDoneIt
{
    /** 
    Add a person to the organizer

    @param p A person object
    */
    public void add(Person p)
    {   
        staff.put(p.getEmail(), p);
        //System.out.println("Person " + p + "added");
    }

    /**
    * Remove a Person from the organizer.
    *
    * @param email The email of the person to be removed.
    */
    public void remove(String email)
    {
        staff.remove(email);
    }

    /**
    * Remove all contacts from the organizer.
    *
    */
    public void empty()
    {
        staff.clear();
    }

    /**
    * Find the person stored in the organizer with the email address.
    * Note, each person will have a unique email address.
    * 
    * @param email The person email address you are looking for.
    *
    */
    public Person findByEmail(String email)
    {
        Person aPerson = staff.get(email);
        return aPerson;
    }

    /**
    * Find all persons stored in the organizer with the same last name.
    * Note, there can be multiple persons with the same last name.
    * 
    * @param lastName The last name of the persons your are looking for.
    *
    */
    public Person[] find(String lastName)
    {
        ArrayList<Person> names = new ArrayList<Person>();

        for (Person s : staff.values())
        {
            if (s.getLastName() == lastName) {
                names.add(s);
            }
        }
        // Convert ArrayList back to Array
        Person nameArray[] = new Person[names.size()];
        names.toArray(nameArray);
        return nameArray;
    }

    /**
    * Return all the contact from the orgnizer in
    * an array sorted by last name.
    * 
    * @return An array of Person objects.
    *
    */
    public Person[] getSortedListByLastName()
    {
        PersonLastNameComparator comp = new PersonLastNameComparator();
        Map<String, Person> sorted = new TreeMap<String, Person>(comp);


        ArrayList<Person> sortedArrayList = new ArrayList<Person>();
      开发者_Python百科  for (Person s: sorted.values()) {
            sortedArrayList.add(s);
        }
        Person sortedArray[] = new Person[sortedArrayList.size()];
        sortedArrayList.toArray(sortedArray);
        return sortedArray;
    }


    private Map<String, Person> staff = new HashMap<String, Person>();

    public static void main(String[] args)
    {
        OrganizeThis testObj = new OrganizeThis();
        Person person1 = new Person("J", "W", "111-222-3333", "JW@ucsd.edu");
        Person person2 = new Person("K", "W", "345-678-9999", "KW@ucsd.edu");
        Person person3 = new Person("Phoebe", "Wang", "322-111-3333", "phoebe@ucsd.edu");
        Person person4 = new Person("Nermal", "Johnson", "322-342-5555", "nermal@ucsd.edu");
        Person person5 = new Person("Apple", "Banana", "123-456-1111", "apple@ucsd.edu");
        testObj.add(person1);
        testObj.add(person2);
        testObj.add(person3);
        testObj.add(person4);
        testObj.add(person5);

        System.out.println(testObj.findByEmail("JW@ucsd.edu"));
        System.out.println("------------" + '\n');

        Person a[] = testObj.find("W");

        for (Person p : a)
        System.out.println(p);

        System.out.println("------------" + '\n');
        a = testObj.find("W");

        for (Person p : a)
        System.out.println(p);

        System.out.println("SORTED" + '\n');
        a = testObj.getSortedListByLastName();
        for (Person b : a) {
            System.out.println(b);
        }

        System.out.println(testObj.getAuthor());
    }
}

class PersonLastNameComparator implements Comparator<Person>
{
    public int compare(Person a, Person b)
    {
        return a.getLastName().compareTo(b.getLastName());
    }
}

And then when I tried doing it by creating an anonymous inner class, I also get a constructor TreeMap cannot find symbol error. Any thoughts?

inner class method:

public Person[] getSortedListByLastName()
    {
        //PersonLastNameComparator comp = new PersonLastNameComparator();
        Map<String, Person> sorted = new TreeMap<String, Person>(new Comparator<Person>()
        {
                public int compare(Person a, Person b)
    {
        return a.getLastName().compareTo(b.getLastName());
    }
    });


        ArrayList<Person> sortedArrayList = new ArrayList<Person>();
        for (Person s: sorted.values()) {
            sortedArrayList.add(s);
        }
        Person sortedArray[] = new Person[sortedArrayList.size()];
        sortedArrayList.toArray(sortedArray);
        return sortedArray;
    }


The comparator should compare the keys, not the values of the map.

That is, your Map contains mappings from String to Person, thus the constructor will expect an argument of type Comparator<? super String>.

To sort them by last name, simply use the last name as key, and the natural ordering of Strings will take care of the rest (no need for an explicit Comparator).


As @aioobe says.

To explain the compilation error in (for example) ...

Map<String, Person> sorted = 
    new TreeMap<String, Person>(new Comparator<Person>() {
        public int compare(Person a, Person b) {
            return a.getLastName().compareTo(b.getLastName());
        }
    });

The compilation error is (in effect) complaining that it cannot find a constructor of type TreeMap<String, Person>(Comparator<Person>). The true type signature of the constructor you are intending to use is:

    TreeMap<K, V>(Comparator<K>)

but what you have written requires a non-existent constructor with signature:

    TreeMap<K, V>(Comparator<V>)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号