【发布时间】:2016-02-18 21:29:45
【问题描述】:
EDIT:方法签名
public Comparable[][] findCommonElements(Comparable[][] collections)
错了。应该是
public Comparable[] findCommonElements(Comparable[][] collections)
但是在我的 IDE 中更改它会搞砸一切。我几乎觉得我已经超出了我的知识范围,因为我不完全理解 Sets,而 2D 数组把我弄得一团糟。
我需要编写一个算法,它采用两个 Comparable 数组,以 线性时间效率 遍历它们,并显示公共元素。 我读过使用 HashSet 会给我最快的时间效率,但我已经陷入僵局。原因如下:
我们得到了指令和一行代码,即方法签名
public Comparable[][] findCommonElements(Comparable[][] collections)
这意味着我必须返回二维数组“集合”。我通过电子邮件向我的教授发送了关于使用 HashSets 的信息,我得到了批准,但我遇到了这个问题:
"您可以在 findCommonElements 方法中使用 HashSets,但您需要能够计算执行的比较次数。虽然散列通常非常有效,但在发生冲突时会进行一些比较。要做到这一点,您将需要访问您使用的 HashSet 的源代码。您还需要 CommonElements 类中的“getComparisons()”方法来返回比较次数。
两个学期的编程,没学过HashSets、Maps、Tables等。我自己在努力学这个,还没有完全理解碰撞。
我的代码确实采用了两个数组并返回了公共元素,但是我的 return 语句很麻烦,因为我基本上是写了它所以它可以编译(二维 Comparable 数组是参数)。
我是否走在正确的道路上?这是代码:
public class CommonElements {
static Comparable[] collection1 = {"A", "B", "C", "D", "E"}; //first array
static Comparable[] collection2 = {"A", "B", "C", "D", "E", "F", "G"}; //second array
static Comparable[][] collections = {collection1, collection2}; //array to store common elements.
static Set<Comparable> commonStuff = new HashSet<>(); //instance of Set containing common elements
public static void main(String[] args) {
CommonElements commonElements = new CommonElements(); //create instance of class CommonElements
commonElements.findCommonElements(collections); //call the find method
}
public Comparable[][] findCommonElements(Comparable[][] collections) {
Set<Comparable> addSet = new HashSet<>(); //instance of Set to add elements to
for (Comparable x : collection1) { //adding elements from first array to my addSet
addSet.add(x);
}
for (Comparable x : collection2) {
if (addSet.contains(x)) {
commonStuff.add(x); //checking for common elements, add to commonStuff Set
}
}
System.out.println(toString(commonStuff)); //print the toString method
return collections; //return statement, otherwise Java will whine at me
}
public String toString(Set<Comparable> commonStuff) { //this method gets rid of the brackets
String elements = commonStuff.toString(); //make a String and assign it to the Set
elements = elements.replaceAll("\\[", "").replaceAll("\\]", ""); //replace both brackets with empty space
return "Common Elements: " + elements; //return the Set as a new String
}
}
【问题讨论】:
-
首先,
Comparable是通用,因此您使用的是 rawtype - 不要。其次,HashSet比较equals-TreeSet比较使用Comparable。使用其中之一。 -
感谢您的建议,但是,在阅读 this 之后,它告诉我 HashSet 在时间复杂度上更快。 ??
-
它们是,但它们只有在你有散列函数时才有效。您拥有
Comparables的事实让我怀疑它不仅仅是Object.hashCode()实现。 -
如果必须恰好接收两个
Comparable[],为什么要将参数定义为Comparable[][]?改为定义两个Comparable[]参数。另外,去掉所有的静态字段,将findCommonElements()设为静态。 -
那么是时候满足要求了。
标签: java arrays hashset comparable