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 3 of 3

Thread: Sorting an Array

  1. #1
    Junior Member
    Join Date
    Feb 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Sorting an Array

    Is it possible to sort an array based on two parameters?

    For ex, can the compare logic be written like this:

    Sort based on the 1st parameter(has more preference), if this is not available then sort based on the 2nd parameter.

    Is it possible to code this logic?


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Sorting an Array

    Yes it is. Simply have your object implement the compareTo method, then implement that type of a comparison inside that method.

  3. #3
    Junior Member
    Join Date
    Feb 2010
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Sorting an Array

    You can also use the sort(T[] a, Comparator<? super T> c) Sorts the specified array of objects according to the order induced by the specified comparator. I believe this will do what you want and it is simplified into one function call.

Similar Threads

  1. [SOLVED] sorting
    By kite98765 in forum Algorithms & Recursion
    Replies: 8
    Last Post: February 4th, 2010, 08:34 AM
  2. Having trouble insert/sorting array values w/ binary searching.
    By bh-chobo in forum Collections and Generics
    Replies: 4
    Last Post: October 8th, 2009, 02:38 AM
  3. [SOLVED] help with sorting...(comparator)
    By mdstrauss in forum Collections and Generics
    Replies: 2
    Last Post: July 26th, 2009, 06:25 AM
  4. [SOLVED] Java program to sort arrays containing dates
    By scottyadam in forum Collections and Generics
    Replies: 1
    Last Post: March 9th, 2009, 06:08 PM