Results 1 to 18 of 18
  1. #1
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Sorting objects in a custom list

    Hi.

    I have a list that can store Mob objects:
    Java Code:
    Mob[] list = new Mob[100]
    What I want done is to sort the Mobs in the list by their num properties.

    I wrote the code to do it as I would if it was a normal ArrayList, but NetBeans will not accept it:

    Java Code:
    Collections.sort(list);
    With the compare method overridden in the Mob class: (Comparator<Mob> is implemented in the Mob class)
    Java Code:
     
    @Override
        public int compare(Mob o1, Mob o2) {
           return o1.num - o2.num;
        }
    Is there someting else I need to, since I'm not using an ArrayList? Or might it be something wrong with my code?

    This is the error I get in NetBeans:
    XML Code:
    no suitable method found for sort(Mob[])
        method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
          (cannot instantiate from arguments because actual and formal argument lists differ in length)
        method Collections.<T#2>sort(List<T#2>) is not applicable
          (no instance(s) of type variable(s) T#2 exist so that argument type Mob[] conforms to formal parameter type List<T#2>)
      where T#1,T#2 are type-variables:
        T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
        T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
    Parashurama

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,590
    Rep Power
    23

    Default Re: Sorting objects in a custom list

    Did you read the API doc for the sort() method you are using? It has some requirements.

    I don't know why the error message shows two args for the sort() method, when the posted code only shows one.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    After reading the API I'm still not sure how to do this right. Ok I need a comparator as a second argument:
    Java Code:
    Collections.sort(list, comparator);
    The API showed two comparators, compare and equals, but non of the following will work.
    Java Code:
    Collections.sort(list, compare);
    Collections.sort(list, equals);
    What is it that I do not get?

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default Re: Sorting objects in a custom list

    It shows whatever options it has for actual exisitng sort() methods.
    There are two of those, one taking a List and the other taking a List and a Comparator.

    As for the OP, the Collections class is part of the Collections framework and is intended to work with Lists and Sets and all that sort of thing, not basic arrays.
    For that you need the Arrays class.
    Please do not ask for code as refusal often offends.

  5. #5
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    So should I use an ArrayList instead of my Mob array?

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,590
    Rep Power
    23

    Default Re: Sorting objects in a custom list

    You could have an array and use the Arrays class's sort() method.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    I will try using an array. Thanks for your help!

  8. #8
    srinivas321 is offline Member
    Join Date
    Sep 2012
    Posts
    2
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    can you paste code once again

  9. #9
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Sorting objects in a custom list

    Quote Originally Posted by srinivas321 View Post
    can you paste code once again
    Why?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Sorting objects in a custom list

    Quote Originally Posted by Parashurama View Post
    I will try using an array. Thanks for your help!
    Try to use more meaningful variable names. Since List<T> is a fairly well known interface from the Collections API, naming an array type variable "list" isn't a good choice.

    Quote Originally Posted by Norm View Post
    I don't know why the error message shows two args for the sort() method, when the posted code only shows one.
    Actually, the error message shows both overloads of Collections#sort(...), neither of which is applicable because list refers to an array.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  11. #11
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    Quote Originally Posted by DarrylBurke View Post
    Try to use more meaningful variable names. Since List<T> is a fairly well known interface from the Collections API, naming an array type variable "list" isn't a good choice.
    Yeah, my original list is named differently, I just simplified it for posting here :)

    I think I worked it out by making a manual sorting function. I have a Moblist that can contain Mob objects, so what I did was:
    1 - Getting mobnumbers from all the mobs in the moblist and put them in an ordinary int[].
    2 - sort the int[]
    3 - get the element index in moblist from its mobnumber and make another moblist where I inserted the mobs in the order in the int[].

    Thanks again everyone, for helping me out!

    -Parashurama-

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default Re: Sorting objects in a custom list

    That seems a little extreme when there is a perfectly good sort() method on the Arrays class (as has been pointed out at least twice in this thread).
    Please do not ask for code as refusal often offends.

  13. #13
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    That might be so, but I was not able to figure out how to get the sort function available in my Moblist class. Tried extending Arrays, but got other errors. And if I were to drop my Moblist class over an array I would have to do alot of rewriting of my code.

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default Re: Sorting objects in a custom list

    But it's the same as the sort method on Collections, and you managed to use that one (barring the compiler error).
    Please do not ask for code as refusal often offends.

  15. #15
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    Ok, I've tried to use arrays from scratch to see if I could figure it out. Here is my code:


    My Room class:
    Java Code:
    public class Room implements Comparable{
    * * String name;
    * * int num;
    //constructor
    * * public Room(){
    * * * * // set values to "" so that the null value dont screw things up
    * * * * num = 99999;
    * * * * name = "Empty";
    * * } **
    * * @Override
    * * public int compareTo(Object o) {
    * * * * Room tmp = (Room)o;
    * * * * if(this.num < tmp.num){
    * * * * * * return -1;
    * * * * }else if(this.num > tmp.num) {
    * * * * * * return 1;
    * * * * }
    * * * * return 0;
    * * }
    }

    Declerations in my main class:
    Java Code:
    static Room rl[] = new Room[10];
    DefaultListModel roomModel = new DefaultListModel();
    MyRoomCellRenderer myRoomRenderer = new MyRoomCellRenderer();
    int rNum = 0;  // Keeps track of how many Rooms are in rl
    Where I add my Room objects
    Java Code:
    Room rTemp = new Room();
    // Read user input and assign room properties
    rTemp.name = txtRoomName.getText();
    rTemp.num = Integer.parseInt(txtRoomNumber.getText()); 
    rl[rNum] = rTemp;
    rNum++;
    
    Arrays.sort(rl);
    roomModel.removeAllElements();
    for(i=0;i<rNum;i++){
        roomModel.addElement(rl[i]);
    }
    listRooms.setCellRenderer(myRoomRenderer);
    listRooms.setModel(roomModel);

    When I try to add Rooms I get this runtime error:
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
    	at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
    	at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
    	at java.util.Arrays.sort(Arrays.java:472)
    	at MUD.MainWindow.btnRoomAddActionPerformed(MainWindow.java:569)
    	at MUD.MainWindow.access$000(MainWindow.java:27)
    	at MUD.MainWindow$1.actionPerformed(MainWindow.java:229)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    	at java.awt.Component.processMouseEvent(Component.java:6505)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    	at java.awt.Component.processEvent(Component.java:6270)
    	at java.awt.Container.processEvent(Container.java:2229)
    	at java.awt.Component.dispatchEventImpl(Component.java:4861)
    	at java.awt.Container.dispatchEventImpl(Container.java:2287)
    	at java.awt.Component.dispatchEvent(Component.java:4687)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    	at java.awt.Container.dispatchEventImpl(Container.java:2273)
    	at java.awt.Window.dispatchEventImpl(Window.java:2719)
    	at java.awt.Component.dispatchEvent(Component.java:4687)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:703)
    	at java.awt.EventQueue.access$000(EventQueue.java:102)
    	at java.awt.EventQueue$3.run(EventQueue.java:662)
    	at java.awt.EventQueue$3.run(EventQueue.java:660)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    	at java.awt.EventQueue$4.run(EventQueue.java:676)
    	at java.awt.EventQueue$4.run(EventQueue.java:674)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:673)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
    If I remove the sorting part, the rest of the code works as it should.

    I used this forumpost as an example:
    Sort java objects in an Array [Archive] - CodingForums.com

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default Re: Sorting objects in a custom list

    Is there anything in your array?
    Please do not ask for code as refusal often offends.

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,590
    Rep Power
    23

    Default Re: Sorting objects in a custom list

    Try writing a small simple program that creates an array with a custom class, adds some instances to an array, prints out the array, calls Arrays.sort() and prints the array after the sort. Compile, execute and post the program and its results here.

    Does the array have any null elements in it?
    Last edited by Norm; 09-14-2012 at 04:46 PM.
    If you don't understand my response, don't ignore it, ask a question.

  18. #18
    Parashurama is offline Member
    Join Date
    Aug 2012
    Posts
    15
    Rep Power
    0

    Default Re: Sorting objects in a custom list

    There we go!

    Silly me, thinking that rl[] was filled with Room objects......
    With the array initsialized and not just declared it worked like a charm :)

    Many thanks to all of you!

Similar Threads

  1. Sorting objects
    By zelenkooo in forum New To Java
    Replies: 4
    Last Post: 06-11-2012, 02:43 PM
  2. Collections sorting a list made of generic class objects
    By andreiutz10 in forum New To Java
    Replies: 5
    Last Post: 02-07-2012, 05:56 PM
  3. Sorting a list
    By sivasiv in forum New To Java
    Replies: 3
    Last Post: 01-10-2012, 08:52 PM
  4. sorting objects in java
    By nn12 in forum New To Java
    Replies: 3
    Last Post: 01-08-2011, 09:18 AM

Posting Permissions

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