我正在开发一个简单的程序,该程序从文件中读取数据并将其放入定义为映射的容器中,其中包含每列的 ArrayList 对象。列的名称放在枚举中。
问题是,ArrayLists是原始的,而我的数据是String类型。
import java.io.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import static lista3.ColumnName.*;
public class Zad2 {
//Name,Surname,Salary,District,Position
Map<ColumnName, ArrayList> columnHolder = new TreeMap<>();
//combination of a map, holding ArrayLists, represents an extendable table.
//Notation holder.get(ColumnName c).get(index j) represents getting the value from specified column
//and row index j
//an iterable holder of columns
private final static ColumnName[] ITERABLE_COLUMN_NAMES = ColumnName.values();
//initialization block for all columns present in ColumnName Enum.
{
for (ColumnName c: ITERABLE_COLUMN_NAMES) {
columnHolder.put(c, new ArrayList<String>());
}
}
}
我的问题是 - 如果我在初始化块中放入 for 循环中 ArrayList 对象的声明并将其放入映射中,它不会引用同一个对象吗?
//initialization block for all columns present in ColumnName Enum.
{
for (ColumnName c: ITERABLE_COLUMN_NAMES) {
ArrayList<String> a = new ArrayList<>();
columnHolder.put(c, a);
}
}
在 for 循环中,您每次都会创建一个全新的ArrayList<String>
,因此它不会引用相同的ArrayList<String>
对象。
在你的代码中,如果你已经在columnHolder
中有一个名为abc
的键,并且你尝试以相同的名称put
另一个ArrayList
,它将覆盖columnHolder
中使用该名称的前一个ArrayList
。这就是地图的作用。