Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java将一个数组排序中的交换应用到另一个数组排序中_Java_Arrays_Sorting - Fatal编程技术网

Java将一个数组排序中的交换应用到另一个数组排序中

Java将一个数组排序中的交换应用到另一个数组排序中,java,arrays,sorting,Java,Arrays,Sorting,假设我有两个数组: int[] foo = new int[] {3, 4, 2, 1, 5}; int[] bar = new int[] {1, 2, 3, 4, 5}; 如果我对foo进行排序,我希望将应用于foo的相同交换应用于bar 所以我会得到这个: int[] new_foo = new int[] {1, 2, 3, 4, 5}; int[] new_bar = new int[] {4, 3, 1, 2, 5}; 我如何轻松地实现它,是否有任何可重用的java方法,这样

假设我有两个数组:

int[] foo = new int[] {3, 4, 2, 1, 5};

int[] bar = new int[] {1, 2, 3, 4, 5};
如果我对foo进行排序,我希望将应用于foo的相同交换应用于bar

所以我会得到这个:

int[] new_foo = new int[] {1, 2, 3, 4, 5};

int[] new_bar = new int[] {4, 3, 1, 2, 5};

我如何轻松地实现它,是否有任何可重用的java方法,这样我就不必亲自实现了?

如果您了解如何对一个数组进行排序,那么在交换第一个数组中的单元格时,只需将条目交换应用于第二个数组即可

伪代码,因为这似乎是一个家庭作业问题:

sort code
if (need to swap cells i and j in Foo) {
  swap foo cell i with cell j
  swap bar cell i with cell j
}
loop end

如果数组1和数组2中的数字属于同一个字段,则可以创建一个包含这两个字段的对象。让我们调用一个具有foo和bar属性的对。然后,我将创建这些对,并按照它们的foo属性对它们进行排序,如下所示:

public class SortPairs {

    static class Pair {
        final int foo;
        final int bar;

        Pair(int foo, int bar) {
            this.foo = foo;
            this.bar = bar;
        }

        @Override
        public String toString() {
            return "Pair{" + "foo=" + foo + ", bar=" + bar + '}';
        }
    }

    public static void main(String[] args) {

        List<Pair> pairs = Arrays.asList(
                new Pair(3, 1),
                new Pair(4, 2),
                new Pair(2, 3),
                new Pair(1, 4),
                new Pair(5, 5));

        System.out.println(pairs);

        Collections.sort(pairs, (pair1, pair2) -> pair1.foo - pair2.foo);
        System.out.println(pairs);
    }
}

在寻求解决方案之前先尝试一下。这就是stackoverflow的全部目的;没想到我会这么说。这只是一个例子。这不是我真正的问题。我无法手动排序大小为500+的列表。我需要能够记录交换并将它们应用到另一个数组,我想知道是否有一种简单的方法可以在java中实现。