I need to sort one array based on the arrangement of another array.
I fetch two arrays from somewhere and they are related.
Firstly, I need to sort the "name" array alphabetically. I can do that easily using "Arrays.sort(name)" but the problem is that my relationship with the "type" array will be lost. I need to re-order the "name" array alphabetically so that my "type" array also gets sorted automatically depending on the "name" array.
My first thought is that it's bad to have two separate arrays. What happens if you get one sorted, 'something bad happens' and you throw an exception... the second one might easily get out of sync.
What I'd do is either put the 'set' into an object - so you'd have an object that contains both a 'type' and a 'name', put those into an array, and sort the one array.
Another option would be to use a map. Use the 'type' as the key, and the 'name' as the value, then sort your keys. Then you can pull your 'name' out in order by key.
Never ascribe to malice that which can be adequately explained by stupidity.
Joined: Nov 07, 2008
I would combine the 2 arrays into a Map or HashMap. Set the Map up to automatically sort alphabetically based on the "name" field. Afterwords if you really need 2 seperate arrays just extract them from the Map using Map.values().toArray(). Check out Map if you are unfamiliar. Also check out Comparable and Comparator examples to see how to automatically sort alphabetically.
~Currently preparing for SCJP6
Joined: Jan 17, 2006
I'm with fred, the existence of parallel arrays almost screams, "Please refactor me into an object!"
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter