【发布时间】:2014-12-22 08:41:18
【问题描述】:
containsKey 和 get 方法有问题,也不确定如何遍历哈希表键和值,我想遍历并将值为 true 的键添加到解决方案列表中
第一个错误:未定义 hashTable 类型的方法 containsKey(int)
第二个错误:只能遍历数组或 java.lang.Iterable 的实例
第三个错误:方法 get(int) 未定义类型 hashTable
package practice;
import java.util.*;
/*
You are given an integer array, where all numbers except for TWO numbers appear even number of times.
Q: Find out the two numbers which appear odd number of times.
*/
public class hashTable{
public static void main(String[] args){
int[] test = {2, 2, 5, 7, 4, 4};
List<Integer> solution = new ArrayList<Integer>();
Hashtable<Integer, Boolean> ht = new Hashtable<Integer, Boolean>();
Boolean check = true;
for (int item : test){
//error if (!containsKey(item)){
check = true;
} else{
check = false;
ht.put(item, check);
}
}
//error for (int item : ht){
//error if (get(item) == true){
solution.add(item);
}
}
System.out.println("the result is");
System.out.println(solution);
}
}
【问题讨论】:
-
从
Hashtable ht = new Hashtable();更改为Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); -
如果你的输入数组总是排序的,就像你的代码一样,你不需要哈希表。您可以通过对输入数组的单次迭代来计算每个整数的出现次数。
-
您使用哈希表有什么特别的原因吗? AFAIR,它已被弃用。改用 HashMap。
-
不,它没有被弃用。自 Java 1.0 以来,大学还没有升级他们的课程,所以这就是他们仍然教授的内容。
-
好的,哈希表现在可以工作了,我如何进行链接以及如何获取哈希表中的链数?我在文档中找不到它