Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Comparator implementation?

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    5
    My Mood
    Where
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Comparator implementation?

    Something about implementing Comparator interface isn't very clear to me: overriding the compare method.

    Like here for example:

    //This sorts a list of objects holding information based on age: the name and the age of the person
     
    public class Person {
     
        String name;
        int age;
     
            public Person (String name, int age)
            {
                this.name = name;
                this.age = age;
            }
     
            public String getName()
            {
                return name;
            }
     
            public int getAge()
            {
                return age;
            }
     
            public String toString() {
                return name+" \t "+age;
            } 
     
               class SomeComparator implements Comparator <Person> //Why use Person for generics?
    	   {
    		public int compare(Person pers1, Person pers2)
    		{
    			int age1 = pers1.getAge();
                            int age2 = pers2.getAge();
     
     
    			if (age1 == age2)
    			{
    				return 0;
    			}
     
    			else if (age1 > age2)
    			{
    				return 1;
    			}
    			else
    			{
    				return -1;
    			}
    		}
    	}
     
     
            public static void main(String[]args) {
                ArrayList<Person> list1 = new ArrayList<Person>();
                list1.add(new Person("Judy", 18));
                list1.add(new Person("Alex", 29));
                list1.add(new Person("Jared", 14));
     
     
                Collections.sort(list1, Collections.reverseOrder(new Person.SomeComparator()));
     
            System.out.println(list1);
            }
    }

    What exactly is happening behind the scenes? I don't understand mostly the part where it returns a 0, a 1, or a -1. After it returns one of those values, what really happens next?

    For the displaying of the list, is the method toString() being accessed to output the list in the System.out.println statement?

    For the generics, why do we use Person?

    That's a lot of questions I know but it is just really substantial for me to get the hang of this. If you could add more key explanations other than those that answer my questions above (I might have missed something else), it would be really appreciated! Thank you in advance!
    Last edited by lorenxvii; March 6th, 2014 at 10:31 AM.


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Comparator implementation?

    Quote Originally Posted by lorenxvii View Post
    public class Person {
     
        String name;
        String age;
     
            public Person (String name, int age)
            {
                this.name = name;
                this.age = age;
            }
     
            public String getName()
            {
                return name;
            }
     
            public int getAge()
            {
                return age;
            }
    First, your Person class is "quite" correct. The main problem is that age instance variable is String but getAge returns an int. This gives you a compilation error!

    Second (less important) declare instances variables as private .


    Quote Originally Posted by lorenxvii View Post
    What exactly is happening behind the scenes? I don't understand mostly the part where it returns a 0, a 1, or a -1. After it returns one of those values, what really happens next?

    For the generics, why do we use Person?
    Just one little note before continue with your questions: it's not very good that you define a comparator implementation into the class of your objects.
    And technically there's also a problem: your SomeComparator is an "inner" class. To instantiate an inner class you must have an instance of the "container" (Person) class. And new Person.SomeComparator() is not correct!

    Please, define the comparator class outside Person (really better in another source code!)

    The Comparator is "generic" just for the type safety in your source code. Who uses the comparator instance (the code into the sort() ) doesn't care about your parametrization. ArrayList simply know to contain Object items. And the sort() simply expects to pass that Objects to parameter 1 and 2 of the compare.

    You can even use Comparator without generics, as in the "old" way (but you have to do some casts).

    Your comparator must only respond about the comparation between 2 Person objects. It's the sort() implementation that makes lots (how many are needed, depending on the sort algorithm) of comparations 2 items per time to deduce and apply the entire order.


    Quote Originally Posted by lorenxvii View Post
    For the displaying of the list, is the method toString() being accessed to output the list in the System.out.println statement?
    Yes. The toString() of ArraysList returns a String that appropriately describes the content of the list.
    Andrea, www.andbin.net SCJP 5 (91%) SCWCD 5 (94%)

    Useful links for Java beginners My new project Java Examples on Google Code

Similar Threads

  1. Problem with Comparator
    By iHank in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 30th, 2013, 05:41 AM
  2. When to use Comparator and Comparable Interface in java
    By diyaots in forum Java Theory & Questions
    Replies: 7
    Last Post: October 26th, 2012, 09:35 AM
  3. Comparator interface question
    By brisingrbrom in forum Collections and Generics
    Replies: 3
    Last Post: February 24th, 2012, 09:54 AM
  4. Replies: 0
    Last Post: October 2nd, 2009, 10:51 PM
  5. [SOLVED] help with sorting...(comparator)
    By mdstrauss in forum Collections and Generics
    Replies: 2
    Last Post: July 26th, 2009, 06:25 AM

Tags for this Thread