[英]Iterating through hashtable and using the get and containsKey methods
在遇到containsKey和get方法時遇到麻煩,也不確定如何遍歷哈希表的鍵和值,我想遍歷並將鍵值為true的鍵添加到解決方案列表中
第一個錯誤:類型hashTable的方法containsKey(int)未定義
第二個錯誤:只能迭代數組或java.lang.Iterable的實例
第三個錯誤:類型為hashTable的方法get(int)未定義
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);
}
}
問題似乎是您使用的是通用類型,而沒有提供通用信息。 如果放置@SuppressWarnings("unchecked")
(或類似的內容,沒有要測試的IDE),則警告應消失。 話雖如此,我建議不要這樣做。
理想情況下,您應該提供常規信息並按照@BackSlash的建議進行操作: Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
。 這將為編譯器提供所需的一般信息,並使您的集合類型安全 ,這是您通常需要的。
話雖這么說,我會建議一種不同的方法:
HashTable<Integer, Boolean>
。 HashTable[number]
的值應用not運算符。 看到您的評論,您可以嘗試如下操作:
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
int[] nums = ...
for(Integer number : nums)
{
if(table.containsKey(number))
{
table.put(number, !table.get(number));
}
else
{
table.put(number, false);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.