Pergunta

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);
Foi útil?

Solução

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

Outras dicas

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])
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top