2014-02-05 47 views
1

我不知道为什么我下得到的错误我put插入到哈希表<字符,列表<Boolean>>

The method put(Character, List<Boolean>) in the type 
Hashtable<Character,List<Boolean>> is not applicable for the arguments (char, boolean) 

我想我所有的匹配类型

这里是我的代码

Hashtable<Character, List<Boolean>> charCheck = 
     new Hashtable<Character, List<Boolean>>(); 
    List<Boolean> used = new ArrayList<Boolean>(); 
    //Set<String> nonDuplicate = new Set<String>(); 
    // make a hashtable of characters used 
    char[] charArray = str.toCharArray(); 
    for (char c : charArray) { 
     charCheck.put(c, used.add(false)); 
+3

你'Hashtable'值意味着是'名单',但你正试图把一个'使用。 add(false)',它返回存储的类型为'Boolean'的前一个值。 –

+2

@SotiriosDelimanolis:更正:'add'返回'boolean',而不是'Boolean',而不管列表的类型如何:它表示列表是否改变。 –

+0

顺便说一句,你为什么使用'Hashtable's而不是'HashMap's? – Mureinik

回答

2

Java中的List#add方法返回boolean指示的值WS是否成功添加到是否。 你应该分开加入了新的元素给它增加一个新的ListMap

Hashtable<Character, List<Boolean>> charCheck = new Hashtable<Character, List<Boolean>>(); 
char[] charArray = str.toCharArray(); 

for (char c : charArray) { 
    List<Boolean> used = charCheck.get(c); 

    // If the char isn't in the map yet, add a new list 
    if (used == null) { 
     used = new ArrayList<Boolean>(); 
     charCheck.put (c, used); 
    } 

    used.add(false); 
} 
+0

加一个正确的答案。 :-) – PNS

1

需要分别对待每ArrayList,即有每Character键一个ArrayList

List<Boolean> used; 

char[] charArray = str.toCharArray(); 

for (char c : charArray) { 

    used = charCheck.get(c); // Get the list of values for this character 

    if (used == null) { // No values stored so far for this character 
     used = new ArrayList<Boolean>(); // Create a new (empty) list of values 
     charCheck.put(c, used); // Add the empty list of values to the map 
    } 

    used.add(false); // Add the value for this character to the value list 
} 

另外,我建议使用的HashMap代替Hashtable

HashMap<Character, List<Boolean>> charCheck = new HashMap<Character, List<Boolean>>(); 
+0

是否有一个原因散列表使用散列表?我读过唯一的区别是性能有点差,因为散列表是线程安全的。 – Liondancer

+0

是的,但这是一个重大的差异。哈希表来自Java的早期版本,所以它已经不再使用了。 HashMap实现也更加高效。换句话说:使用一个HashMap。 :-) – PNS

+0

会做老板! – Liondancer

相关问题