Question

Sorting ArrayList Objects.

Asked by: sunny08

Hi,

     Below is the class which sorts the list of strings and integers. I passed the arguments as 115R 1125R 147C 37R 57R 37C and it shows the result as 1125R 115R 147C 37C 37R 57R. But the problem is I want the output as 37C 37R 57R 115R 147C 1125R. Can anyone help me with this. Its really important.

import java.util.*;

public class SortArrayList
{      
      public static void main(String s[])
      {  
            Collections col;
            List l = sort(s);
            
            System.out.println("\nStrings sorted List ...");
            for(int i = 0; i < s.length; i++)
            {
                  System.out.println((String)l.get(i));
            }
            
            int ints[] = {
                                    11, 2, -22, 401, 6
                                    };
            
            Integer in[] = new Integer[ints.length];            
            for(int i = 0; i < in.length; i++)
            {
                  in[i] = new Integer(ints[i]);
            }
            
            l = sort(in);
            System.out.println("\nIntegers sorted List ...");
            
            for(int i = 0; i < in.length; i++)
            {
                  System.out.println((Integer)l.get(i));
            }
    }
      
    public static List sort(Object o[])
    {
            ArrayList al = new ArrayList();
            for(int i = 0; i < o.length; i++)
            al.add(i, o[i]);
            List list = Collections.synchronizedList(al);
            Collections.sort(list);
            return list;
    }
}



Thanks.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-12-10 at 07:27:50ID21237976
Tags

arraylist

,

sort

Topic

Java Programming Language

Participating Experts
2
Points
250
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ArrayList
    I have an error of incompatiable types in the following code and just can't seem to figure it out. Can anyone lend me a hand? Here is the code: /* * readDictionaryFile.java * * Created on November 3, 2004, 12:46 AM */ /** * * @author Shannon DM Rice ...
  2. arraylist?
    Is an arraylist the best way to do this? If so how do I get my items out of my array list? I'm a java developer (thrust into a new language with a short time frame) and I'm ued to Vectors and Enumerations.... ArrayList al = new System.Collections.ArrayList(); try { ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: zzynxPosted on 2004-12-10 at 07:40:26ID: 12793180

Try replacing

Collections.sort(list);

by

Collections.sort(list, new Comparator() {

     public int compare(Object o1, Object o2) {
          String s1 = (String)o1;
          String s2 = (String)o2;

          String integer1[] = s1.split("[0-9]");
          String integer2[] = s2.split("[0-9]");
          String chars1[] = s1.split("[^0-9]");
          String chars2[] = s2.split("[^0-9]");

          Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
          Integer i2 = new Integer( Integer.parseInt(integer2[0]) );
   
          if (i1.equals(i2)
             return chars1[1].compareTo(chars2[1]);
          else
             return i1.compareTo(i2);
     }
});

 

by: zzynxPosted on 2004-12-10 at 07:42:05ID: 12793202

>> Its really important.
Maybe you could have considered 500pts ;°)

 

by: zzynxPosted on 2004-12-10 at 07:46:45ID: 12793272

Wait a minute... that's not OK...

 

by: zzynxPosted on 2004-12-10 at 07:50:00ID: 12793319

Correction:

Collections.sort(list, new Comparator() {

     public int compare(Object o1, Object o2) {
          String s1 = (String)o1;
          String s2 = (String)o2;

          String integer1[] = s1.split("[^0-9]");      // <<<<<  changed
          String integer2[] = s2.split("[^0-9]");      // <<<<<  changed
          String chars1[] = s1.split("[0-9]+");         // <<<<<  changed
          String chars2[] = s2.split("[0-9]+");         // <<<<<  changed

          Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
          Integer i2 = new Integer( Integer.parseInt(integer2[0]) );
   
          if (i1.equals(i2)
             return chars1[1].compareTo(chars2[1]);
          else
             return i1.compareTo(i2);
     }
});

 

by: zzynxPosted on 2004-12-10 at 07:51:21ID: 12793335

I assumed that your list contains Strings like "115R", "1125R", "147C", "37R", "57R", "37C",...

 

by: AceMcCloudPosted on 2004-12-10 at 08:17:48ID: 12793640

zzynx is 100% correct that you should use a comparator, but you might find a simpler impelementation more readable.

I'm also not a big fan of anonymous inner class (they clutter the code something awful IMO).
 
Something like this would work just as well:

Collections.sort(list, new SpecialComarator());

Class SpecialComparator
implements Comparator
{
     public int compare(Object o1, Object o2)
    {
        String s1 = (String)o1;
        String s2 = (String)o2;

         int offset1 = findCharOffset(s1);
         int offset2 = findCharOffset(s2);

         int v1 = Integer.parseInt(s1.substring(0,offset1));
         int v2 = Integer.parseInt(s2.substring(0,offset2));

        int difference = v1 - v2;

        if (difference != 0)
        {
            return difference;
        }

        return s1.substring(offset1).compareTo(s2.substring(offset2));
    }

    private int findCharOffset(String value)
    {
        integer result = 0;
        while (result < value.length() && Character.isDigit(value.charAt(result))
        {
             result++;
        }

        return result;
    }
}

 

by: zzynxPosted on 2004-12-10 at 08:24:03ID: 12793720

>> I'm also not a big fan of anonymous inner class
In this case I find an inner class is on it's place: It's here that you need the sorting; it's here that you find the Comparator class.
But, that's a matter of taste of course ;°)

>>...but you might find a simpler impelementation more readable.
Well, it's a matter of being/making yourself familiar with regular expressions.
In the past I also wasn't a big fan of them.
But once you discover their power...

 

by: sunny08Posted on 2004-12-10 at 08:26:58ID: 12793757

Hi zzynx,

        Thank you for the quick response. I executed the code which shows the result as 1125R 115R 147C 37C 37R 57R. but I need the result as 37C 37R 57R 115R 147C 1125R. Can you help me with this.


Thanks.

 

by: zzynxPosted on 2004-12-10 at 08:34:45ID: 12793853

Are you sure?
For me it just works:

        List list = new ArrayList();
        list.add("1125R");
        list.add("115R");
        list.add("147C");
        list.add("37C");
        list.add("37R");
        list.add("57R");
        Collections.sort(list, new Comparator() {

             public int compare(Object o1, Object o2) {
                  String s1 = (String)o1;
                  String s2 = (String)o2;

                  String integer1[] = s1.split("[^0-9]");      // <<<<<  changed
                  String integer2[] = s2.split("[^0-9]");      // <<<<<  changed
                  String chars1[] = s1.split("[0-9]+");         // <<<<<  changed
                  String chars2[] = s2.split("[0-9]+");         // <<<<<  changed

                  Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
                  Integer i2 = new Integer( Integer.parseInt(integer2[0]) );

                  if (i1.equals(i2))
                     return chars1[1].compareTo(chars2[1]);
                  else
                     return i1.compareTo(i2);
             }});
        System.out.println("\nStrings sorted List ...");
        for(int i = 0; i < list.size(); i++) {
               System.out.println((String)list.get(i));
        }

Output:
Strings sorted List ...
37C
37R
57R
115R
147C
1125R

 

by: zzynxPosted on 2004-12-10 at 08:35:22ID: 12793860

I'm going offline. Success.

 

by: AceMcCloudPosted on 2004-12-10 at 08:38:08ID: 12793896

>>>...but you might find a simpler impelementation more readable.
> Well, it's a matter of being/making yourself familiar with regular expressions.
> In the past I also wasn't a big fan of them.
> But once you discover their power...

Sure, regular expressions are powerful things and I know full well HOW to use them. I'm not conviced that they are the most appropriate solution in this case - they're TOO powerful and unnecessarily complicate an essentially simple problem.

An of course, that too is a matter of taste. I'm a card carrying member of "Do The Simplest Thing That Could Possibly Work".

Actually thinking about it more clearly, something like this would also work:

Class SpecialComparator
implements Comparator
{
     public int compare(Object o1, Object o2)
    {
        String s1 = (String)o1;
        String s2 = (String)o2;

         int v1 = Integer.parseInt(s1.substring(0,s1.length() - 1));
         int v2 = Integer.parseInt(s2.substring(0,s2.length() - 1));

        int difference = v1 - v2;

        if (difference != 0)
        {
            return difference;
        }

        return Character.getNumericValue(s1.charAt(length() - 1) -
                 Character.getNumericValue(s2.charAt(length() - 1);
    }

 

by: sunny08Posted on 2004-12-10 at 08:48:50ID: 12793997

Hi,

     I am not getting the write output. I don't think this is working, but hey thanks for the response. I appreciate that.

Thanks.

 

by: zzynxPosted on 2004-12-11 at 04:08:35ID: 12799372

>> I am not getting the write output
You mean with what I posted? Impossible. It just works for me!
It outputs:
37C
37R
57R
115R
147C
1125R

Can you show us the exact code you have for the moment? There must be something wrong with it...

 

by: sunny08Posted on 2004-12-12 at 18:28:31ID: 12806171

Hi zzynx,
         
        Here is the exact code which I have. Please help me with this. Here is the arguments which I passed while executing 115R 1125R 147C 37R 57R 37C and I am getting the output as  1125R 115R 147C 37C 37R 57R. Below is the code:


import java.util.*;

public class SortObjects
{      
      public static void main(String s[])
      {  
            Collections col;
            List l = sort(s);
            
            System.out.println("\nStrings sorted List ...");
            for(int i = 0; i < s.length; i++)
            {
                  System.out.println((String)l.get(i));
            }
            
            int ints[] = {
                                    11, 2, -22, 401, 6
                                    };
            
            Integer in[] = new Integer[ints.length];            
            for(int i = 0; i < in.length; i++)
            {
                  in[i] = new Integer(ints[i]);
            }
            
            l = sort(in);
            System.out.println("\nIntegers sorted List ...");
            
            for(int i = 0; i < in.length; i++)
            {
                  System.out.println((Integer)l.get(i));
            }
    }
      
    public static List sort(Object o[])
    {
            ArrayList al = new ArrayList();
            for(int i = 0; i < o.length; i++)
            al.add(i, o[i]);
            List list = Collections.synchronizedList(al);
            
            Collections.sort(list, new Comparator()
            {

            public int compare(Object o1, Object o2)
            {
                                   
                  String s1 = (String)o1;
                String s2 = (String)o2;

                int v1 = Integer.parseInt(s1.substring(0,s1.length() - 1));
                int v2 = Integer.parseInt(s2.substring(0,s2.length() - 1));

                int difference = v1 - v2;

                if (difference != 0)
                {
                    return difference;
                }

                return Character.getNumericValue(s1.charAt(s1.length() - 1)) -
                         Character.getNumericValue(s2.charAt(s1.length() -1));
                  
            }
        });
      
            //Collections.sort(list , new SpecialComparator());
            
            System.out.println("\nStrings sorted List ...");
            
            for(int i = 0; i < list.size(); i++)                        
          System.out.println((String)list.get(i));
            
            return list;
    }
   
}


Thanks in advance.

 

by: sunny08Posted on 2004-12-12 at 19:07:48ID: 12806281

hi,


    I have tried this code too.


/*
 * Created on Dec 10, 2004
 *
 * @author z688240
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

import java.util.*;

public class SortObjects
{      
      public static void main(String s[])
      {  
            Collections col;
            List l = sort(s);
            
            System.out.println("\nStrings sorted List ...");
            for(int i = 0; i < s.length; i++)
            {
                  System.out.println((String)l.get(i));
            }
            
            int ints[] = {
                                    11, 2, -22, 401, 6
                                    };
            
            Integer in[] = new Integer[ints.length];            
            for(int i = 0; i < in.length; i++)
            {
                  in[i] = new Integer(ints[i]);
            }
            
            l = sort(in);
            System.out.println("\nIntegers sorted List ...");
            
            for(int i = 0; i < in.length; i++)
            {
                  System.out.println((Integer)l.get(i));
            }
    }
      
    public static List sort(Object o[])
    {
            ArrayList al = new ArrayList();
            for(int i = 0; i < o.length; i++)
            al.add(i, o[i]);
            List list = Collections.synchronizedList(al);
            
            Collections.sort(list, new Comparator()
            {

            public int compare(Object o1, Object o2)
            {
                 String s1 = (String)o1;
                 String s2 = (String)o2;

                 String integer1[] = s1.split("[^0-9]");      // <<<<<  changed
                 String integer2[] = s2.split("[^0-9]");      // <<<<<  changed
                 String chars1[] = s1.split("[0-9]+");         // <<<<<  changed
                 String chars2[] = s2.split("[0-9]+");         // <<<<<  changed

                 Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
                 Integer i2 = new Integer( Integer.parseInt(integer2[0]) );

                 if (i1.equals(i2))
                    return chars1[1].compareTo(chars2[1]);
            }
        });
      
      
            System.out.println("\nStrings sorted List ...");
            
            for(int i = 0; i < list.size(); i++)                        
          System.out.println((String)list.get(i));
            
            return list;
    }
   
 
}

 

by: zzynxPosted on 2004-12-13 at 00:04:37ID: 12807062

Hi sunny,
this should work (I felt free to remove all obsolete stuff):

/*
 * SortObjects.java
 *
 * Created on 13 december 2004, 8:47
 */

import java.util.*;

public class SortObjects
{    
     public static void main(String s[])
     {
        // The input is a String array. Make that an ArrayList:
        List inputList = new ArrayList(Arrays.asList(s));
       
        List l = sort(inputList);
         
        System.out.println("\nStrings sorted List ...");
        for(int i = 0; i < l.size(); i++)
            System.out.println((String)l.get(i));
    }
     
    public static List sort(List list) {
          Collections.sort(list, new Comparator() {

            public int compare(Object o1, Object o2) {
                 String s1 = (String)o1;
                 String s2 = (String)o2;

                 String integer1[] = s1.split("[^0-9]");      // <<<<<  changed
                 String integer2[] = s2.split("[^0-9]");      // <<<<<  changed
                 String chars1[] = s1.split("[0-9]+");         // <<<<<  changed
                 String chars2[] = s2.split("[0-9]+");         // <<<<<  changed

                 Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
                 Integer i2 = new Integer( Integer.parseInt(integer2[0]) );

                 if (i1.equals(i2))
                    return chars1[1].compareTo(chars2[1]);
                  else
                     return i1.compareTo(i2);
            }
        });
        return list;
    }
}

But in fact, I wouldn't even make that a separate function:

/*
 * SortObjects.java
 *
 * Created on 13 december 2004, 8:47
 */

import java.util.*;

public class SortObjects
{    
     public static void main(String s[])
     {
        // The input is a String array. Make that an ArrayList:
        List inputList = new ArrayList(Arrays.asList(s));
       
        Collections.sort(inputList, new Comparator() {

            public int compare(Object o1, Object o2) {
                 String s1 = (String)o1;
                 String s2 = (String)o2;

                 String integer1[] = s1.split("[^0-9]");
                 String integer2[] = s2.split("[^0-9]");
                 String chars1[] = s1.split("[0-9]+");
                 String chars2[] = s2.split("[0-9]+");

                 Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
                 Integer i2 = new Integer( Integer.parseInt(integer2[0]) );

                 if (i1.equals(i2))
                    return chars1[1].compareTo(chars2[1]);
                  else
                     return i1.compareTo(i2);
            }
        });
         
        System.out.println("\nStrings sorted List ...");
        for(int i = 0; i < inputList.size(); i++)
            System.out.println((String)inputList.get(i));
    }
}

 

by: sunny08Posted on 2004-12-13 at 06:23:41ID: 12809349

Hello zzynx,

         I really appreciate the response but I don't know, I already tried the code 2 days back without writing different function and different possibilities. But it doesn't work for me. The arguments which I passed are 115R 1125R 147C 37R 57R 37C and u seem to get the output as expected but I get different output which is different from what I want which is weird. The output which I got is :

Strings sorted List ...
1125R
115R
147C
37C
37R
57R

        Can you send me the code which u executed on ur side.

Thanks

 

by: zzynxPosted on 2004-12-13 at 06:56:54ID: 12809619

>>Can you send me the code which u executed on ur side
Sure. (But in fact I already did)

This is my SortObject.java file:


import java.util.*;

public class SortObjects
{    
     public static void main(String s[])
     {
        String t[] = { "115R", "1125R", "147C", "37R", "57R", "37C" };  // This is to simulate the user input
       
        // The input is a String array. Make that an ArrayList:
        List inputList = new ArrayList(Arrays.asList(t));          // replace "t" by "s" for using the command line arguments
       
        List l = sort(inputList);
         
        System.out.println("\nStrings sorted List ...");
        for(int i = 0; i < l.size(); i++)
            System.out.println((String)l.get(i));
    }
     
    public static List sort(List list) {
          Collections.sort(list, new Comparator() {

            public int compare(Object o1, Object o2) {
                 String s1 = (String)o1;
                 String s2 = (String)o2;

                 String integer1[] = s1.split("[^0-9]");      // <<<<<  changed
                 String integer2[] = s2.split("[^0-9]");      // <<<<<  changed
                 String chars1[] = s1.split("[0-9]+");         // <<<<<  changed
                 String chars2[] = s2.split("[0-9]+");         // <<<<<  changed

                 Integer i1 = new Integer( Integer.parseInt(integer1[0]) );
                 Integer i2 = new Integer( Integer.parseInt(integer2[0]) );

                 if (i1.equals(i2))
                    return chars1[1].compareTo(chars2[1]);
                  else
                     return i1.compareTo(i2);
            }
        });
        return list;
    }
}

The output of this program is:
Strings sorted List ...
37C
37R
57R
115R
147C
1125R

 

by: zzynxPosted on 2004-12-13 at 08:01:30ID: 12810309

So? You have found the problem?
Thanks for accepting

 

by: sunny08Posted on 2004-12-22 at 09:09:33ID: 12885608

Hi zzynx,

      I have some problem with the code, I am getting an exception as below:

java.lang.ArrayIndexOutOfBoundsException: 0
      at SortObjects$1.compare(SortObjects.java:44)
      at java.util.Arrays.mergeSort(Arrays.java:1278)
      at java.util.Arrays.sort(Arrays.java:1219)
      at java.util.Collections.sort(Collections.java:155)
      at SortObjects.main(SortObjects.java:24)
Exception in thread "main"

and the code is as below:


import java.util.*;

public class SortObjects
{    
    public static void main(String s[])
    {
        String t[] = { "NITT", "A123" };  
       
        List inputList = new ArrayList(Arrays.asList(t));          
        //ArrayList inputList = new ArrayList(Arrays.asList(s));
       
        if(inputList != null && inputList.size() > 0)
        {
              Collections.sort(inputList, new Comparator()
              {
                  public int compare(Object o1, Object o2)
                  {
                       String s1 = (String)o1;
                       String s2 = (String)o2;
                      
                       String integer1[] = s1.split("[^0-9]");
                       String integer2[] = s2.split("[^0-9]");
      
                       String chars1[] = s1.split("[0-9]+");
                       String chars2[] = s2.split("[0-9]+");
      
                       Integer i1 = new Integer(Integer.parseInt(integer1[0]));
                                 Integer i2 = new Integer(Integer.parseInt(integer2[0]));
          
                       if (i1.equals(i2))
                          return chars1[1].compareTo(chars2[1]);
                        else
                           return i1.compareTo(i2);
                  }
              });
        }
         
        System.out.println("\nStrings sorted List ...");
        for(int i = 0; i < inputList.size(); i++)
            System.out.println((String)inputList.get(i));
    }
}

Please help me with this.

Thanks in advance.
Sunny

 

by: zzynxPosted on 2004-12-23 at 00:01:39ID: 12890689

Well, the code I gave you was for sorting items of the following format: "<number><characters>"
Now, apparently want to sort items of these formats "<characters only>" and "<characters><number>".
The code should be adapted for that.

 

by: sunny08Posted on 2005-03-28 at 09:49:43ID: 13645332

Hi zzynx, I am having some problem with this program. I tried so many ways for fixing this but no luck. I need help with this problem. Below is the code:

import java.util.*;

public class SortObjects
{
      public static ArrayList getSortedList(ArrayList sortableList)
      {
            if(sortableList != null)
            {
                  if(sortableList.size() == 0)
                        return sortableList;
            }
            else
                  return sortableList;
      
            List inputList = sortableList;
            Collections.sort(inputList, new Comparator()
            {
                  public int compare(Object o1, Object o2)
                  {
                        String s1 = (String)o1;
                        String s2 = (String)o2;
                        System.out.println("$$$$$$$$$s1 : "+s1+"   s2:"+s2);
      
                        String integer1[] = s1.split("[^0-9]");
                        String integer2[] = s2.split("[^0-9]");
                        String chars1[] = s1.split("[0-9]+");
                        String chars2[] = s2.split("[0-9]+");
      
                        Integer i1 = null;
                        Integer i2 = null;
                        String str1 = null;
                        String str2 = null;
      
                        if(integer1.length > 0 && integer2.length > 0)
                        {
                              try
                              {
                                    i1 = new Integer(Integer.parseInt(integer1[0]));
                                    i2 = new Integer(Integer.parseInt(integer2[0]));
                              }
                              catch(NumberFormatException e)
                              {
                                    if(chars1.length > 0 && chars2.length > 0)
                                    {
                                          str1 = chars1[0];
                                          str2 = chars2[0];
                                    }
                              }
                        }
                        else if(chars1.length > 0 && chars2.length > 0)
                        {
                              str1 = chars1[0];
                              str2 = chars2[0];
                        }
                        System.out.println("i1 :"+i1.intValue()+"   i2 :"+i2.intValue());
                        if(i1 != null && i2 != null)
                        {
                              System.out.println("%%%%%%%%");
                              if (i1.equals(i2))
                              {
                                    System.out.println("%%%%%%%%1111 chars1[1] :"+str1);
                                    System.out.println("%%%%%%%%%  chars2[1] :"+str2);
                                    if(chars1[1] != null && chars2[1] != null)
                                          return chars1[1].compareTo(chars2[1]);
                                    else
                                          return 0;
                              }
                              else
                              {      
                                    System.out.println("%%%%%%%%2222222222");
                                    return i1.compareTo(i2);
                              }
                        }
                        else if(str1 != null && str2 != null)
                        {      
                              if(str1.equals(str2))
                                    return chars1[1].compareTo(chars2[1]);
                              else
                                    return str1.compareTo(str2);
                        }
                        return 0;
                  }
            });
            return (ArrayList)inputList;
      }
      
      public static void main(String[] args)
      {
            SortObjects sTest  = new SortObjects();
            ArrayList list = new ArrayList();
            list.add("011");
            list.add("011A");
            list.add("011AB");
            list.add("011AA");
            ArrayList sList = getSortedList(list);
            for(int i=0; i < sList.size(); i++)
            {
                  System.out.println("i value :"+i+"    data :"+(String)sList.get(1));
            }
      }
}

Exception which I am getting is :

$$$$$$$$$s1 : 011   s2:011A
i1 :11   i2 :11
%%%%%%%%
%%%%%%%%1111 chars1[1] :null
%%%%%%%%%  chars2[1] :null
java.lang.ArrayIndexOutOfBoundsException: 1
      at SortObjects$1.compare(SortObjects.java:68)
      at java.util.Arrays.mergeSort(Arrays.java:1278)
      at java.util.Arrays.sort(Arrays.java:1219)
      at java.util.Collections.sort(Collections.java:155)
      at SortObjects.getSortedList(SortObjects.java:21)
      at SortObjects.main(SortObjects.java:100)
Exception in thread "main"

any help would be appreciated.

Thanks in advance

 

by: zzynxPosted on 2005-03-29 at 03:46:20ID: 13651467

1) You should have posted another question concerning this
2) How do you want the given list to be sorted? What are the rules?

 

by: sunny08Posted on 2005-03-29 at 07:43:15ID: 13653305

hey zzynx, thanks for responding but I was able to resolve that problem. Anyway, I appreciate it, Thanks

 

by: zzynxPosted on 2005-03-30 at 00:29:52ID: 13659906

>> I was able to resolve that problem
Good!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...