2015-04-19 137 views
1

最近,当做大学的任务时,我遇到的一件事是排序和搜索一个2D数组。 使用Arrays.sort(example);Arrays.binarySearch(example, "xyz");返回错误:java二维数组 - 排序和搜索

example cannot be cast to java.lang.Comparable

代替二进制搜索的,我不得不嵌套的for循环使用,虽然我也喜欢做的有效途径。

我的另一个问题是使用Arrays.asList(example).contains("xyz");,它似乎从来没有工作。然后我用System.out.println(Arrays.asList(example));来检查什么是错的。这是我的了:

[[[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected]]

那是什么,最重要的是什么是解决这些问题的最佳方式是什么?

而跟进的问题 - 为什么有些错误(如example cannot be cast to java.lang.Comparable只出现一次的程序运行,而不是当它被编译

任何帮助是非常赞赏

+1

如果你表现出一些更多的代码的这会有所帮助,具体在哪里,你填充阵列和什么 – tddmonkey

+0

排序的二维数组没有什么意义。你会如何分类'{{1,4},{2,3}}?“? +++ *与二进制搜索相比,我不得不使用嵌套for循环,尽管我希望这样做的有效方式。* - 二进制搜索是有效的,但只在已经*排序的数组上。如果添加分类成本,则不支付。 – maaartinus

回答

2

java.util.Arrays,除了deepHashCodedeepEquals,不递归操作数组。

例:

int[ ][ ] arr = new int[ h ][ w ]; 
Arrays.sort(arr); \\ Sorts int[ ] not ints 
Arrays.asList(arr); \\ Returns List< int[ ] > 

排序二维阵列相对于整个数组不作一大堆的道理,你会过得更好只是把它作为一维数组。二进制搜索二维数组也是一样。

如果你想排序对象有两种方法来做到这一点。最好的方法是让课程实施java.lang.Comparable。如果您不能编辑该类或想要提供多种方法来排序对象,则可以实施java.util.Comparator并将其实例传递给Arrays.sort

为了排序或搜索使用java.util.Arrays阵列的对象的类型必须要么实现的你java.lang.Comparable必须提供的java.util.Comparator一个实例的阵列。请记住,它必须与在数组第一级找到的对象的类型相同。

例:

int[ ]  arr1 = ...; \\ Type of first level is int 
int[ ][ ] arr2 = ...; \\ Type of first level is int[ ] 
int[ ][ ][ ] arr3 = ...; \\ Type of first level is int[ ][ ] 
+0

是有道理的。谢谢你的帮助。 – Yulek

1

第一个问题?

example cannot be cast to java.lang.Comparable

的项目在example应该实现Comparable接口和覆盖的方法Compare()否则Arrays.sort()将不会“知道”按照哪个顺序对您的物品进行分拣。

问题二,打印显示为:

[[[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected], [[email protected]] 

从中实例化example元素也应该覆盖的方法toString()为了得到你打印什么的一个很好的代表类。

+0

但它不能,因为它是一个'int []'。 – maaartinus

+0

@maaartinus你为什么这么认为?他有一个例子,查找'.contains(“xyz”)' – alfasin

+0

因为'I'意思是'int',并且因为'[I @ some_numbers'是数组的标准'toString'输出。主要是因为OP写的关于'排序和搜索2D数组'和'int [] []'只是一个int数组的数组。 – maaartinus