Page 1 of 3 123 LastLast
Results 1 to 20 of 49
  1. #1
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default Priority Queue experts needed !!!

    Hi:

    I'm having trouble storing more than one objects into Java's built-in PQ. Here is my code:

    PriorityQueue<Person> pq2 = new PriorityQueue<Person>( );
    Person dan = new Person("Dan", 44 );
    Person john = new Person("john", 50);

    pq2.add(john);
    pq2.add(dan);

    /*When I try to print the whole pq2, it gets stuck. It works only when I add only one object(either john or dan) into the queue. I thought by default pq2 can hold 11 elements, so why can't I have 2 elements in the queue?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by niu_niu View Post
    Hi:

    I'm having trouble storing more than one objects into Java's built-in PQ. Here is my code:

    PriorityQueue<Person> pq2 = new PriorityQueue<Person>( );
    Person dan = new Person("Dan", 44 );
    Person john = new Person("john", 50);

    pq2.add(john);
    pq2.add(dan);

    /*When I try to print the whole pq2, it gets stuck. It works only when I add only one object(either john or dan) into the queue. I thought by default pq2 can hold 11 elements, so why can't I have 2 elements in the queue?
    Have you implemented the Comparable interface for your Person class?

    kind regards,

    Jos

  3. #3
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    Can you please tell me how to implement the comparable interface in the Person class?

    Here is my Person class.
    class Person {
    public String name;
    public int age;
    Person( ) {
    }
    public Person(String name, int age) {
    this.name = name;
    this.age =age;
    }
    }

  4. #4
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    and why do I even need a comparable interface in order to store objects in the PQ? I don't need it to store <Integer> or <Strings> etc...so why elements like Objects???

  5. #5
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    import java.util.*;
    import acm.program.*;

    class PersonComparator implements Comparator<Person> {
    public int compare(Person p1, Person p2) {
    if (p1 == p2)
    return 0;
    return p1.age - p2.age;
    }
    }

    public class testPQ extends ConsoleProgram {
    public void run ( ){

    int[ ] intArr1 = {4,6,7,4,2};
    PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>( );
    for (int i=0; i< intArr1.length; i++)
    pq1.add(intArr1[i]);
    System.out.println("pq1 is: " + pq1);

    Person dan = new Person("Dan", 44 );
    Person john = new Person("john", 50);
    Person[ ] person1={dan, john, new Person("Josh", 45), new Person("Bill", 66)};

    //PriorityQueue<String> pq2 = new PriorityQueue<String>( );
    PriorityQueue<Person> pq2 = new PriorityQueue<Person>( );

    //pq2

    //System.out.println("pq2 is: " + pq2);
    System.out.println("person1[0] is: " + person1[0].toString());
    System.out.println("person1[1] is: " + person1[1]);

    //String str = person1[0].toString();
    //System.out.println("str is: " + str);

    pq2.add(john);
    pq2.add(dan);

    //pq2.add(john);
    //System.out.println("pq2 size is: " + pq2.size());
    System.out.println("pq1 is: " + pq1);
    System.out.println("pq2 is : " + pq2);


    // System.out.println("person1 is: " + person1);
    // System.out.println("person1 0 contains : " + person1[0]);
    // System.out.println("person1 1 contains : " + person1[1]);
    // System.out.println("person1 2 contains : " + person1[2]);
    //
    // pq2.add(dan);
    // //pq2.add(john);
    //
    // //for (int i=0; i<person1.length; i++)
    // //pq2.add(person1[0]);
    // //pq2.add(person1[1]);
    // //pq2.add(person1[2]);
    //
    // System.out.println("pq2 is: " + pq2);
    // System.out.println("where?");
    // System.out.println(pq2.contains(dan));

    }
    }

    class Person {
    public String name;
    public int age;
    Person( ) {
    }
    public Person(String name, int age) {
    this.name = name;
    this.age =age;
    }
    }

  6. #6
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default

    Please use code tags when posting code! You can do this by highlighting code and clicking the "#" button, top right of the editor.

    Comparable (Java 2 Platform SE v1.4.2) explains the comparable interface.

    Java Code:
    class Person implements Comparable {
        private String name;
        private int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age =age;
        }
    
        /**
         * Compares this object with the specified object for order.
         * 
         * @param o the object to compare to the person
         * @return a negative integer, zero, or a positive integer as this object
         *          is less than, equal to, or greater than the specified object.
         */
        public int compareTo(Object o) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * @return the age
         */
        public int getAge() {
            return age;
        }
    
        /**
         * @param age the age to set
         */
        public void setAge(int age) {
            this.age = age;
        }
    }
    The comparable interface is needed for a priority queue to give it a priority... Without the interface the queue is just that: a queue.

    Note I also changed your code to make the fields private and gave you some get and set methods. Although not necessary, it is advisable and good practice! It also makes things much clearer, honest!

    Hope this helps,
    Berkeleybross

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by niu_niu View Post
    and why do I even need a comparable interface in order to store objects in the PQ? I don't need it to store <Integer> or <Strings> etc...so why elements like Objects???
    um.... did you know that Integer and String both in fact implement Comparable?

  8. #8
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    it still is not working. here is the code.

    import java.util.*;
    import acm.program.*;

    public class PQLoosers extends ConsoleProgram {
    public void run ( ){

    Person1 dan = new Person1("Dan", 44 );
    Person1 john = new Person1("john", 50);

    PriorityQueue<Person1> pq2 = new PriorityQueue<Person1>( );

    pq2.add(dan);

    System.out.println("pq2 is: " + pq2);

    pq2.add(john);
    System.out.println("pq2 is : " + pq2);
    }
    }

    class Person1 implements Comparable {
    public String name;
    public int age;

    public Person1(String name, int age) {
    this.name = name;
    this.age =age;
    }

    public int compareTo(Object o) {
    throw new UnsupportedOperationException("Not supported yet.");
    }
    }


    After executing the above program, I got the following result:
    ------------------------------
    Console output:
    pq2 is: [Person1@1702c48]
    ------------------------------

    if you notice, after I added the second element-pq2.add(john), it got stuck, and print pq2 didn't give any result. Still, it doesn't take two elements.

  9. #9
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default

    Please use code tags when posting code! You can do this by highlighting code and clicking the "#" button, top right of the editor.


    Please come back when you have read the links i provided.

    Also, read the code i gave you. I did not do everything for you as this is a forum for tips not answers.

    The code throws an unsupportedOperationException meaning you need to implement it.

    I dont mean to sound rude but I feel a bit put out that i helped you and all you did was cut out some code without reading / trying to understand it. Copying the code means you dont learn anything.

    I also note you decided to cut out the javadoc i wrote - which you were meant to read and understand what you had to do.

    Please come back when you have implemented, or tried to implement, the compareTo method. Ill be happy to help if you have shown at least some effort.

    Again, sorry if im sounding harsh.
    Berkeleybross

  10. #10
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default


    After executing the above program, I got the following result:
    ------------------------------
    Console output:
    pq2 is: [Person1@1702c48]
    This means that you need to give the Person class a logical toString() method because it is outputting the default method from Object.

  11. #11
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    I know it is just an address. that's fine. but the problem is, doesn't it suppose to print out the address of the 2nd object I added?

  12. #12
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    I appreciate your help. I will do the code paste. this is my first thread on this forum.
    I will try to understand the code when I see it works. I am a beginner. I have done google search before I posted here.

  13. #13
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by niu_niu View Post
    I know it is just an address. that's fine. but the problem is, doesn't it suppose to print out the address of the 2nd object I added?
    When the compareTo method and toString methods were fixed, your program seems to work OK for me.

  14. #14
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    If I don't need this "toString" method for displaying one element in pq2, why do I need it in order to display the 2nd element???

  15. #15
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default

    Java Code:
    /**
         * Compares this object with the specified object for order.
         * 
         * @param o the object to compare to the person
         * @return a negative integer, zero, or a positive integer as this object
         *          is less than, equal to, or greater than the specified object.
         */
        public int compareTo(Object o) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    As the javadoc says, you need to make the method return an integer.

    First you should check if they are both of type Person - you can do that by using the
    instanceof keyword. i.e.

    Java Code:
    if (o instanceof person) {
        // do more checks
    } else {
        throw new Exception ("Wrong class");
    }
    
    // I havent checked if this code works so may be wrong
    if they are both Persons (People? :P) then you should check against each field. If you think one person is a higher priority then return a positive integer, if they are the same priority return zero etc.

    Im fairly sure if you implement the compareTo method properly then the priority queue will accept both Dan *and* john :)

    I hope this helps and sorry for being abrupt in the last post.
    Berkeleybross

  16. #16
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default

    Quote Originally Posted by niu_niu View Post
    If I don't need this "toString" method for displaying one element in pq2, why do I need it in order to display the 2nd element???
    You're right, you dont need it. The problem is the 2nd element is not being put into the queue due to the faulty compareTo method.

    However, it is recommended you do a simple toString method:

    Java Code:
    public String toString  () {
        return this.name + ", " + this.age;
    }
    You don't *need* it as such, but it will help you identify which objects have been placed in the queue.

    For all you know, John could be in the queue but not Dan. Or vice versa. Knowing these kind of things comes in handy for debugging later.

    It may seem like a waste of time right now - like the get and set methods - but they are recommended for a reason!

    Berkeleybross

  17. #17
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    Got it. I will give the faulty method another try. I have failed several times. no apologies. you replied and helped me. those who didn't shouldn't apologize! Just kidding...but I am stupid, if it doesn't work, i will post again.

  18. #18
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    no luck. same result.

    Java Code:
    import java.util.*;
    import acm.program.*;
    
    public class PQLoosers extends ConsoleProgram {
    	public void run ( ){	
    		
    	Person1 dan = new Person1("Dan", 44 );
    	Person1 john = new Person1("john", 50); 
    		
    	PriorityQueue<Person1> pq2 = new PriorityQueue<Person1>( ); 
    
    	pq2.add(dan); 
      
        System.out.println("pq2 is: " + pq2);
        
        pq2.add(john); 
    	
        System.out.println("pq2 is : " + pq2); 	
    	}
    }
    
     class Person1 {
    	public String name; 
    	public int age;
    	
    	public Person1(String name, int age) {
    		 this.name = name; 
    		 this.age =age; 
    	}
    	public int CompareTo(Person1 p1, Person1 p2) {
    		 if (p1 == p2)
    	    	  return 0; 
    	      return p1.age -p2.age; 
    	}
    	}
    	
    class PersonComp implements Comparator<Person1> {
            public int compare(Person1 p1, Person1 p2) {
    		      if (p1 == p2)
    		    	  return 0; 
    		      return p1.age -p2.age; 
    		    } 
    	}

  19. #19
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default

    Firstly, a big thankyou for using code tags! Its so much easier to read :P

    Ok, so. Scrap "PersonComp", Person1 needs to be implementing Comparator.

    All you need it to do is make it return a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the given object.

    The priority queue itself calls your objects compareTo method and then prioritises the queue according to this result.

    I've provided an example on how you may want to implement it, but it is far from a perfect solution. It does however, compile, run, and fill the priority queue. You will probably want to edit it to suit your needs.

    And i recommend you keep the get and set methods this time. I've even thrown in the toString method for you. :D

    I hope you understand it eventually, feel free to ask if you dont understand anybit of it.
    Berkeleybross



    Java Code:
    class Person1 implements Comparable {
        private String name;
        private int age;
    
        public Person1(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        /**
         * Compares this object with the specified object for order.
         *
         * @param o the object to compare to the person
         * @return a negative integer, zero, or a positive integer as this object
         *          is less than, equal to, or greater than the specified object.
         */
        public int compareTo(Object o) {
            // Check if o is of type person1
            if (o instanceof Person1) {
                // typecast o to a person1
                Person1 temp = (Person1) o;
                return this.name.compareTo(temp.name);
            } else {
                throw new RuntimeException ("wrong class");
            }
        }
    
        /**
         * @return a string with the persons name and age
         */
        @Override
        public String toString () {
             return (this.name + ": " + this.age);
        }
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * @return the age
         */
        public int getAge() {
            return age;
        }
    
        /**
         * @param age the age to set
         */
        public void setAge(int age) {
            this.age = age;
        }
    }

  20. #20
    niu_niu is offline Member
    Join Date
    Jun 2010
    Posts
    48
    Rep Power
    0

    Default

    Java Code:
    import java.util.*;
    import acm.program.*;
    
    public class PQLoosers extends ConsoleProgram {
    	public void run ( ){	
    		
    	Person1 dan = new Person1("Dan", 44 );
    	Person1 john = new Person1("john", 50); 
    		
    	PriorityQueue<Person1> pq2 = new PriorityQueue<Person1>( ); 
    
    	pq2.add(dan); 
      
        System.out.println("pq2 is: " + pq2);
        
        pq2.add(john); 
    	
        System.out.println("pq2 is : " + pq2); 	
    	}
    }
    
     class Person1 {
    	public String name; 
    	public int age;
    	
    	public Person1(String name, int age) {
    		 this.name = name; 
    		 this.age =age; 
    	}
    
    	public int compareTo(Object o) {
            // Check if o is of type person1
            if (o instanceof Person1) {
                // typecast o to a person1
                Person1 temp = (Person1) o;
                return this.name.compareTo(temp.name);
            } else {
                throw new RuntimeException ("wrong class");
            }
        }
     }
    result:
    pq2 is: [Person1@8a52b6]

    for some reason, it still is printing pq2 once.

Page 1 of 3 123 LastLast

Similar Threads

  1. priority
    By simorgh in forum Threads and Synchronization
    Replies: 4
    Last Post: 01-07-2012, 12:49 AM
  2. Priority Queue Question
    By Taz_84 in forum New To Java
    Replies: 0
    Last Post: 01-29-2009, 03:23 AM
  3. How to implement Priority queue with Java
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-12-2008, 08:49 PM
  4. How to get/set thread priority
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-09-2008, 06:40 PM
  5. Java experts needed- 30 minute online Java projects
    By michelle in forum Jobs Offered
    Replies: 0
    Last Post: 03-05-2008, 11:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •