The output of the code below is this map: {1=[Dd, Ff], 2=[Dd, Ff], 3=[Dd, Ff], 4=[Dd, Ff]}?

huangapple go评论101阅读模式
英文:

Why the output of the code below is this map:{1=[Dd,Ff], 2=[Dd,Ff], 3=[Dd,Ff], 4=[Dd,Ff]}?

问题

以下是翻译好的内容:

"我期望的输出是这样的:{1=[Aa,Cc], 2=[Bb,Dd], 3=[Cc,Ee], 4=[Dd,Ff]}?
我只想为数组中的每个字母(除了第一个和最后一个字母)创建单独的数组列表,然后将这些数组列表作为映射中的值放入。"

import java.util.ArrayList;
import java.util.HashMap;

public class Demo {
    public static void main(String[] args) {
        String[] arr = {"Aa", "Bb", "Cc", "Dd", "Ee", "Ff"};
        ArrayList<String> al = new ArrayList<>();
        HashMap<Integer, ArrayList<String>> mp = new HashMap<>();

        for (int i = 1; i < 5; i++) {
            al.clear();
            al.add(arr[i - 1]);
            al.add(arr[i + 1]);
            mp.put(i, al);
        }

        System.out.print(mp);
    }
}
英文:

What I anticipated as output was this:{1=[Aa,Cc], 2=[Bb,Dd], 3=[Cc,Ee], 4=[Dd,Ff]}?
I just wanted to make separate array lists with the adjacent letters for every letter from the array(except for the first and the last ones), and then to put these array lists as values in a map.

import java.util.ArrayList;
    import java.util.HashMap;
    public class Demo{
    public static void main(String[] args){
    		String[] arr = {&quot;Aa&quot;, &quot;Bb&quot;, &quot;Cc&quot;, &quot;Dd&quot;, &quot;Ee&quot;, &quot;Ff&quot;};
    		ArrayList&lt;String&gt; al = new ArrayList&lt;&gt;();
    		HashMap&lt;Integer,ArrayList&lt;String&gt;&gt; mp = new HashMap&lt;&gt;();
    		
    		for(int i = 1; i &lt; 5; i++){
    			al.clear(); 
    			al.add(arr[i-1]);
    			al.add(arr[i+1]);
    			mp.put(i,al);
    		}
    		
    		System.out.print(mp);
    	}
    }

答案1

得分: 1

"这段代码并不是为了创建多个数组列表。在循环中,不是清空列表,而是创建一个新的列表。"

"for (int i = 1; i < 5; i++) {
al = new ArrayList<>();
...
}"

英文:

> I just wanted to make separate array lists

That's not what this code does. This code makes one array list.

In the loop, instead of clearing the list, create a new one.

 for (int i = 1; i &lt; 5; i++) {
   al = new ArrayList&lt;&gt;();
   ...

huangapple
  • 本文由 发表于 2020年7月23日 01:01:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63039505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定