0

我有一个 ints[] 列表,我一次列出一个。我发现了一个有趣的模式,结果似乎颠倒了,所以为了测试它,我颠倒了进入我的方法的列表,然后显示它们,发现它们匹配。我想以编程方式找到它们,但是当我将列表本身打印为字符串时,即使项目/订单匹配,结果也不匹配。

这是方法(它只是获取数据,颠倒顺序并打印两者..没什么花哨的):

private static void show (int [] arr) { 
    //before we print results lets reverse the list and study if there's something we can do to make this go faster
    int[] ReversedList = new int[arr.length];
    for (int x = arr.length-1, y=0; x>=0;x--, y++) {
        ReversedList[y] = arr[x];
    }
    for (int x = 0; x < arr.length; x++) {
        //System.out.print (" " + (arr [x] + low[x]));
        System.out.print (" " + (arr[x]));
    }
    System.out.println (" " + arr.toString());
    for (int x = 0; x < ReversedList.length; x++) {
        //System.out.print (" " + (arr [x] + low[x]));
        System.out.print (" " + (ReversedList[x]));
    }

    System.out.println (" " + ReversedList.toString() + "  ***");
   //System.out.println("*****************");
}

但字符串不匹配。这是输出的一个片段(*表示它被颠倒了):

 0 0 0 20 [I@199a0c7c
 20 0 0 0 [I@50a9ae05  ***
....
 20 0 0 0 [I@1e9af0b1
 0 0 0 20 [I@4e300429  ***

它们都是这样的,我不确定为什么它们相同时不匹配(至少看起来相同)。我有一个名为的数组列表results,它包含所有的 int[] 并且我尝试执行 results.indexof(reversed) 但没有运气(我得到的所有内容都是'-1')。我怎样才能找到匹配项?

4

3 回答 3

4

您正在查看您拥有的 int 数组的地址。数据是相同的,但数据存储在多个位置,因为您使用的是多个实例。

要比较数组,请使用Arrays.equals(int[], int[]). 或者,您可以使用更好的格式查看数组中的信息Arrays.toString(int[])

于 2012-05-26T03:37:39.427 回答
2

这些都是对象地址。它们引用不同的整数数组,因此它们不会匹配。

请改用该java.util.Arrays.toString(int[])方法来直观地查看数组的内容:

import java.util.Arrays;
// ... code
System.out.println (" " + Arrays.toString(arr));
于 2012-05-26T03:33:35.307 回答
-3

What is getting printed is the HASHCODE. It is like both are separate objects and are stored separately on the heap memory. HashCode is nothing but unique number allocated to each object by the JVM. I hope this is what you are looking for.

于 2012-05-26T03:38:48.363 回答