java - Priority Queue Sorting String -
i need use priorityqueue sort person objects.
the person class:
public class person implements comparable<person>{ private string firstname; private string lastname; public person(string firstname, string lastname){ this.firstname = firstname; this.lastname = lastname; } public string getfirstname() {return firstname;} public string getlastname() {return lastname;} public string tostring(){ return "name: " + firstname + " " + lastname + "\n"; } public int compareto(person p){ string pname1 = firstname + lastname; string pname2 = p.firstname + p.lastname; return pname1.compareto(pname2); }
the main code:
import java.util.priorityqueue; public class priorityq{ public static void main(string[] args){ priorityqueue<person> pers = new priorityqueue<person>(); pers.add(new person("sam", "smith")); pers.add(new person("charlie", "black")); pers.add(new person("betty", "brown")); pers.add(new person("jessica", "stewart")); pers.add(new person("john", "friday")); pers.add(new person("frank", "folcy")); system.out.print(pers); } }
i need to:
- print without sort (already done in main)
- sort last name
- sort first name, last name
i must not change code in person class.
i created new class:
import java.util.comparator; public class lastnamecomparator implements comparator<person>{ public int compareto(person a, person b){ person p1 = (person)a; person p2 = (person)b; if(p1.getlastname().equals(p2.getlastname())) { return p1.getfirstname().compareto(p2.getfirstname()); } return p1.getlastname().compareto(p2.getlastname()); } }
it has compile error:
lastnamecomparator.java:2: error: lastnamecomparator not abstract , not override abstract method compare(person,person) in comparator
first have remove comparable interface
person class
, implementations: try this:
import java.util.comparator; public class lastnamecomparator implements comparator<person>{ @override public int compare(person o1, person o2) { return o1.lastname.compareto(o2.lastname); } }
and in main method
following sort last name:
collections.sort(pers,new lastnamecomparator()); iterator<person> = pers.iterator(); while(it.hasnext()){ system.out.println(it.next()); }
Comments
Post a Comment