Sorting an int array, tied to a string array in Java

I have two arrays:

int[] intArray = new int[]{point1,point2,point3,point4};

String[] strArray = new String[]{worda,wordb,wordc,wordd};

Now, I want to sort intArray in numerical order, such that strArray follows the same order. I'm sure this is a common problem, but I can't get it to work. I made a TreeMap and added the values in from each array. Shouldn't a TreeMap automatically sort by the key, intArray[]? It doesn't appear to work.

        TreeMap theMap = new TreeMap();

        theMap.put(intArray, strArray);

Answers


Yes a TreeMap should work fine. However instead of adding both arrays add the each pair of values.

theMap.put(point1, worda);
theMap.put(point2, wordb);
theMap.put(point3, wordc);
theMap.put(point4, wordd);

You are confusing how a TreeMap is used. TreeMap keeps the keys sorted. In your case you have one key - intArray so there is nothing to be sorted. You have to put every pair into the map: theMap.put(intArray[i], strArray[i]) for every possible i.

By the way, if it is only for the sorting you don't need obligatory a TreeMap. You can make a list of a class which wraps a point and a string and then sort it with Collections.sort(list). Of course you have to implement Comparable interface.


for(int i=0; i< intArray.length; i++)
  theMap.put(intArray[i],strArray[i])

Need Your Help

Why can't I get Apache's CustomLog directive to work?

apache logging ubuntu

I'm trying to use Apache's CustomLog directive to create some custom log files, but can't get it working. Here is the configuration I'm using for the custom logs:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.