Java语言根据一个数组的关联,sort可以实现关联的数组的排序么

Java语言根据一个数组的关联,去对另一个数组进行排序的实现,用什么方法,sort可以实现关联的数组的排序么?还是需要用什么语句

如果楼上得sort不能实现,你或许可以考虑自定义对象数组或利用索引,这个数组里要包含两个数组元素,靠着第一个数组的关联对对象数组进行排序,在根据对象数组的排序顺序重新排列第二个数组。

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        int[] array1 = {3, 1, 4, 2};
        String[] array2 = {"C", "A", "D", "B"};
        CustomObject[] customObjects = new CustomObject[array1.length];
        for (int i = 0; i < array1.length; i++) {
            customObjects[i] = new CustomObject(array1[i], array2[i]);
        }

        // 根据自定义对象数组的排序规则进行排序
        Arrays.sort(customObjects);
        for (int i = 0; i < array2.length; i++) {
            array2[i] = customObjects[i].getValue();
        }
        System.out.println(Arrays.toString(array1));
        System.out.println(Arrays.toString(array2));
    }

    static class CustomObject implements Comparable<CustomObject> {
        private int value1;
        private String value2;

        public CustomObject(int value1, String value2) {
            this.value1 = value1;
            this.value2 = value2;
        }

        public String getValue() {
            return value2;
        }

        @Override
        public int compareTo(CustomObject other) {
            return Integer.compare(this.value1, other.value1);
        }
    }
}

在Java中,如果你想根据一个数组的关联来对另一个数组进行排序,你可以使用Arrays.sort()方法,并结合Comparator接口来实现自定义的排序规则。


import java.util.Arrays;
import java.util.Comparator;

public class AssociatedArraySort {
    public static void main(String[] args) {
        // 示例关联数组
        int[] array1 = {1, 3, 2, 4, 5};
        String[] array2 = {"A", "B", "C", "D", "E"};

        // 创建关联信息对象数组
        AssociatedItem[] items = new AssociatedItem[array1.length];
        for (int i = 0; i < array1.length; i++) {
            items[i] = new AssociatedItem(array1[i], array2[i]);
        }

        // 使用自定义比较器进行排序
        Arrays.sort(items, new AssociatedComparator());

        // 输出排序结果
        for (AssociatedItem item : items) {
            System.out.print(item.value + " ");
        }
    }

    // 关联信息对象
    static class AssociatedItem {
        int key;
        String value;

        public AssociatedItem(int key, String value) {
            this.key = key;
            this.value = value;
        }
    }

    // 自定义比较器类
    static class AssociatedComparator implements Comparator<AssociatedItem> {
        @Override
        public int compare(AssociatedItem item1, AssociatedItem item2) {
            return Integer.compare(item1.key, item2.key);
        }
    }
}