英文:
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 = {"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);
}
}
答案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 < 5; i++) {
al = new ArrayList<>();
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论