使用HashMaps Java

Ali*_*Ali 1 java hashmap

我正在编写一个方法,允许我计算String类型的元素在String类型的LinkedList中出现的次数.我的代码如下所示不起作用.我继续在下面评论的行中获得索引超出界限.似乎无法找到这个bug

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;
}
Run Code Online (Sandbox Code Playgroud)

使用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());
}
Run Code Online (Sandbox Code Playgroud)

我的代码应该通过链表找出列表中元素出现的次数,并同时从列表中删除重复项.然后打印元素及其在列表中出现的次数.我昨晚发布了这个帖子,但还没有得到答复.对不起,重新发布.

rge*_*man 6

你正在运行列表的末尾.更改

for(int i =0; i<=test.size() && test.get(i)!=null; i++){ 
Run Code Online (Sandbox Code Playgroud)

for(int i =0; i< test.size() && test.get(i)!=null; i++){ 
Run Code Online (Sandbox Code Playgroud)

一个有效的索引List(或阵列)是0通过size() - 1.