我正在将数据库文件写入bus_stopdb.properties
文件。它看起来像这样:(这是文件的一部分)
2X-bound1-stop0-stopcode=CH42W09500
2B-bound1-stop2-stopseq=2
11C-bound2-stop14-stopname=\u725B\u982D\u89D2\u9435\u8DEF\u7AD9
11D-bounds=2
13D-bound2-stop31-stopcode=SA14S32000
11D-bound1-stop17-stopname=\u89C0\u5858\u78BC\u982D
11D-bound2-stop9-stopcode=KW16W22500
2A-bound1-stop29-stopcode=ME01T11000
14D-bound1-stop18-stopcode=LE01W13000
11X-bound1-stop12-stopseq=12
16-bound1-stop3-stopseq=3
23M-bound1-stop12-stopseq=12
我将把属性文件的内容加载到List<String[]>
。但我发出的问题是List
的内容是相同。这是加载文件的功能:
public static boolean loadDatabase(boolean fromClassResources){
try {
File file;
Properties prop = new Properties();
InputStream in;
if (fromClassResources){
in = KmbApi.class.getClassLoader().getResourceAsStream("bus_stopdb.properties");
} else
{
file = new File("bus_stopdb.properties");
if(!file.exists()){
return false;
}
in = new FileInputStream(file);
}
prop.load(in);
int buses = Integer.parseInt(prop.getProperty("buses"));
int bounds;
int stops;
String[] data = new String[5];
for (int i = 0; i < buses; i++){
data[0] = bus_db[i];
bounds = Integer.parseInt(prop.getProperty(bus_db[i] + "-bounds"));
for (int j = 1; j <= bounds; j++){
System.out.println("Bus: " + bus_db[i] + " Bound: " + j);
try {
stops = Integer.parseInt(prop.getProperty(bus_db[i] + "-bound" + j + "-stops"));
} catch (NullPointerException e){
continue;
}
data[1] = Integer.toString(j);
for (int s = 0; s < stops; s++){
data[2] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopcode");
data[3] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopseq");
data[4] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopname");
//Printing the building array
System.out.println(Arrays.deepToString(data));
busstop_pair.add(data);
}
}
}
//Printing the arrays in the List<String[]>
System.out.println(Arrays.deepToString(busstop_pair.toArray()));
in.close();
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
第一个println
正在给我一个正确的结果(不同的结果)。
但是第二个println
给了我一个不变的结果,它们都是一样的!
我无法弄清楚代码发生了什么。
答案 0 :(得分:2)
您要多次向List添加相同的数组。您必须为循环的每次迭代创建一个新数组,以便在List中包含不同的元素:
for (int s = 0; s < stops; s++){
data = new String[5];
data[0] = bus_db[i];
data[1] = Integer.toString(j);
data[2] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopcode");
data[3] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopseq");
data[4] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopname");
//Printing the building array
System.out.println(Arrays.deepToString(data));
busstop_pair.add(data);
}