【问题标题】:Java: sort one array to another using method and comparatorJava:使用方法和比较器将一个数组排序到另一个数组
【发布时间】:2014-08-02 05:02:00
【问题描述】:

我试图更好地理解比较器接口 在 Java 中与对象和类交互。

我有一个未排序单词的字符串数组。 我想将该数组复制到第二个数组 并按字母顺序第二个数组。

当我调用 Array.sort 方法时 并传入第二个数组和比较器对象作为参数, 两个数组最终按字母顺序排序 我不明白为什么????

这是一个例子:

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

public class test2 {

    public static void main(String[] args) {

        // first array is unsorted
        String[] words_unsorted = { "the", "color", "blue", "is", "the",
                "color", "of", "the", "sky" };
        // copy array to another array to be sorted
        String[] words_sorted = words_unsorted;
        // instantiate a reference to a new Comparator object
        Comparator<String> listComparator = new Comparator<String>() { 
            public int compare(String str1, String str2) {
                return str1.compareTo(str2);
            }
        };
        // invoke sort method on words_sorted array 
        Arrays.sort(words_sorted, listComparator);      
        // compare arrays / 
        int size = words_sorted.length;
        for(int i = 0; i < size; i++) {     
            System.out.println(words_unsorted[i] + " " + words_sorted[i]);          
        }       
    }
}

输出:

blue blue
color color
color color
is is
of of
sky sky
the the
the the
the the

【问题讨论】:

  • 你没有两个数组。您对 same 数组有两个 references。另外Arrays.sort()作用于你传入的数组;你不能将一个数组传递给Arrays.sort() 并得到另一个数组。

标签: java arrays string sorting comparator


【解决方案1】:

String[] words_sorted = words_unsorted; 只是让words_sorted 指向与words_unsorted 相同的内存位置,这意味着您对其中任何一个所做的任何更改都会反映在另一个上

相反,您可以使用类似...的方式复制数组

System.arraycopy(words_unsorted, 0, words_sorted, 0, words_unsorted.length);

【讨论】:

    【解决方案2】:

    只有一个数组,words_sortedwords_unsorted 指的是同一个数组,因为您在这里将一个引用分配给了另一个:

    String[] words_sorted = words_unsorted;
    

    您将需要数组本身的副本,而不是对数组的引用的副本。使用Arrays.copyOf通过复制旧数组来创建一个新数组。

    String[] words_sorted = Arrays.copyOf(words_unsorted, words_unsorted.length);
    

    【讨论】:

      猜你喜欢
      • 2017-04-27
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多