Sorting Parallel Arrays in Java

后端 未结 5 672
青春惊慌失措
青春惊慌失措 2021-01-21 06:19

I have two arrays, one stores the distance of the cities and the other stores the corresponding population. Everything works fine if the distance of the cities is in ascending o

5条回答
  •  不要未来只要你来
    2021-01-21 06:49

    The correct solution is this. However if you want a completely mad hack, you can do this:

    public final class ParallelIntArrays extends AbstractList {
    
        private final int[] array1;
        private final int[] array2;
    
        public ParallelIntArrays(int[] array1, int[] array2) {
            if (array1.length != array2.length)
                throw new IllegalArgumentException();
            this.array1 = array1;
            this.array2 = array2;
        }
    
        @Override
        public int[] get(int i) {
            return new int[] { array1[i], array2[i] };
        }
    
        @Override
        public int size() {
            return array1.length;
        }
    
        @Override
        public int[] set(int i, int[] a) {
            if (a.length != 2)
                throw new IllegalArgumentException();
            int[] b = get(i);
            array1[i] = a[0];
            array2[i] = a[1];
            return b;
        }
    }
    

    Then you can do:

    int[] city = {5,   1,  2,    4,   3   };
    int[] pop =  {100, 30, 4000, 400, 5000};
    new ParallelIntArrays(city, pop).sort(Comparator.comparingInt(arr -> arr[0]));
    System.out.println(Arrays.toString(city));
    System.out.println(Arrays.toString(pop));
    

    Note that as written above, ParallelIntArrays does not function correctly as a List. For example list.contains(list.get(0)) would give false. If you made it a List or a List> instead, it would be fixed.

提交回复
热议问题