java - 使用 HashMaps Java

标签 java hashmap

我正在编写一个方法,该方法允许我计算字符串类型的元素在字符串类型的 LinkedList 中出现的次数。我下面显示的代码不起作用。在我下面评论的行中,我一直在获取索引越界。似乎找不到错误

public int findDuplicate (LinkedList<String> e) {
int j = 1;
LinkedList<String> test = e;
while (!test.isEmpty()){
    test = e;
    String value = test.pop();
    //Screws up here when i = 6 
    for(int i =0; i<=test.size() && test.get(i)!=null; i++){ 
        String value3 = test.get(i);
        if(e.get(i).equals(value) && i<=test.size()){
            String value2 = test.get(i); 
            j++;
            String Duplicate = e.get(i);
            e.remove(i);
        }
    }
    System.out.println(value + " is listed " + j + " times");

}
return j;
}

使用 hashmaps.. 仍然不起作用

public void findDuplicate (LinkedList e) {

    Map<String,Integer> counts = new HashMap<String,Integer>();

    while(!e.isEmpty()){
        String value = e.pop();
        for(int i =0; i<e.size(); i++){
            counts.put(value, i);
        }
    }
    System.out.println(counts.toString());
}

我的代码应该遍历链表找出列表中的元素出现了多少次并同时从列表中删除重复项。然后打印元素及其在列表中出现的次数。我昨晚发布了这个,但还没有得到回复。抱歉重新发布。

最佳答案

您快跑到列表的末尾了。改变

for(int i =0; i<=test.size() && test.get(i)!=null; i++){ 

for(int i =0; i< test.size() && test.get(i)!=null; i++){ 

List(或数组)的有效索引为 0size() - 1

关于java - 使用 HashMaps Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15211626/

相关文章:

java - 可以在资源尝试中返回连接对象

java - 线程、锁和条件的状态

java - 解压缩时 FileOutputStream 抛出 FileNotFoundException

java - 迭代值时的 HashMap 线程安全

java - 在 HashMap 中添加到 List 的快捷方式

java - 我正在使用 toString() 方法将 map 转换为字符串。有没有办法可以将字符串转换回 map ?

Java 堆分析因 SIGABRT 崩溃

java - 为什么 JAVA 中的 BIGInteger 对更高的幂没有响应?

ruby-on-rails - 有没有一种不太尴尬的方法来在 Ruby 哈希中存储值?

java - 将文本中的字符串替换为 HashMap 中键的值