我对下面的代码有疑问。我正在阅读一个包含大量数据的文件,其中一些内容是无关紧要的。数据写在一行,所以我不能使用nextLine或其他东西。
对于每个vertex
,我将相关信息保存到dataperpoint
。当我转到下一个顶点时,我想清除列表以填充新的相关信息。
我遇到的问题是,每次清除dataperpoint
时,地图中的所有值都会被清除。当我尝试填充它时,Map中之前的所有位置都会得到相同的值。
我该如何做,并确保每个vertex
都能获得自己的列表?
期待您的建议!
public static Map<Integer, List<Double>> readData(File f) // throws IO exception?
{
// Create Map to store the vertex and list with relevant information in
List<Double> dataperpoint = new ArrayList<Double>();
Map<Integer, List<Double>> data = new HashMap<>();
// Open the scanner
try (Scanner in = new Scanner(f))
{
// To make sure the correct localization is used
in.useLocale(Locale.US);
// The first six integers contain irrelevant information
for (int step = 1; step <= 6; step++)
{
in.nextInt();
}
// Do the information for vertex 0 separately, since it has one data point less
int vertex = in.nextInt();
for (int doubleinfo = 1; doubleinfo <= 4; doubleinfo++) // six relevant variables
{
dataperpoint.add(in.nextDouble());
}
// irrelevant information
for (int irrelevantinfo = 1; irrelevantinfo <= 2; irrelevantinfo++)
{
in.nextInt();
}
// Opening and Closing of time window
dataperpoint.add((double) in.nextInt());
dataperpoint.add((double) in.nextInt());
data.put(vertex, dataperpoint);
while (in.hasNext()) // think of different statement later
{
dataperpoint = new ArrayList<Double>();
vertex = in.nextInt();
for (int doubleinfo = 1; doubleinfo <= 4; doubleinfo++) // six relevant variables
{
dataperpoint.add(in.nextDouble());
}
// irrelevant information
for (int irrelevantinfo = 1; irrelevantinfo <= 3; irrelevantinfo++)
{
in.nextInt();
}
// Opening and Closing of time window
dataperpoint.add((double) in.nextInt());
dataperpoint.add((double) in.nextInt());
data.put(vertex, dataperpoint);
}
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
答案 0 :(得分:0)
使用LinkedHashMap&lt;&gt;而不是HashMap&lt;&gt;它应该解决你的问题。阅读此Difference between HashMap, LinkedHashMap and TreeMap