2

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);
0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This assumes all int values are unique, any duplicates will be lost.
1

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);

Comments

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

5 Comments

you may want to check before iteration if(intArray.length>strArray.length) throw new IllegalStateException()
It will throw an exception any way so I am not sure the extra check is needed.
@Peter Lawrey. Yes It will, I wanted to convey that be aware. :)
I would add assert intArray.length == strArray.length; to convey this.
@Peter Lawrey ah, yeah. This is better. Thanks. I improved a bit. :) I'd almost forgaotten that assert is also a tool available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.