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

go评论73阅读模式

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();
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();
mp.put(i,al);
}

System.out.print(mp);
}
}
``````

# 答案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;();
...
``````

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

go 41

go 42

go 42

go 48