JAVA: sorting 2 arrays based on 1 array

Discussion in 'Programming' started by samir s, Mar 28, 2013.

  1. #1
    hi, in my java program there are 2 arrays like-

    int[] num = {3,5,1,7,2};
    String[] name = {"jo", "sam", "jo", "tom", "rach"};

    each arrays have same length & in a specific order

    now if I sort num array using Arrays.sort(num) it only sort num array, name array remain unchanged. Same way Arrays.sort(name)...

    the out put of the above array is like this:

    3 = jo
    5 = sam
    1 = jo
    7 = tom
    2 = rach


    now I want a code, so when I sort by "num" array (name array will automatic be sorted), output shud be like this

    1 = jo
    2 = rach

    3 = jo
    5 = sam
    7 = tom



    then again, when I sort by "name" array (num will be sorted automatically) output-

    1 = jo

    3 = jo
    2 = rach
    5 = sam
    7 = tom

    how can I do it?
    plz someone help
     
    samir s, Mar 28, 2013 IP
  2. matessim

    matessim Active Member

    Messages:
    514
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    70
    #2
    You should use a Map which correlates a key(the num) with the value (the string), which is pretty much what you want as far as i understand.
    Further Reading.
     
    matessim, Mar 30, 2013 IP