【发布时间】:2011-05-15 03:40:33
【问题描述】:
进行了一次数据库调用,结果是一堆行,包含两个类型为 A 和 B 的字符串列。例如(x_a, y_b), (x_a, y1_b), (x2_a,y_b)
我们的想法是提出一个映射列表,例如 {(x_a,{y_b,y1_b}), (x2_a,{y_b})},其中类型 A 的对象不重复,并在从数据库中提取结果的同时执行此操作。
这是我尝试过的:
int i =0;
List<String> type2 = new ArrayList<String>();
Map<String,List<String>> type1_type2 = new HashMap<String,List<String>>();
List<Map> list_type1_type2 = new ArrayList<Map>();
String [] type1Array = new String[100];
String [] type2Array = new String[100];
int trackStart = 0;
while (res.next()){
String type1 = res.getString(1);
String type2 = res.getString(2);
type1Array[i]=type1;
type2Array[i] = type2;
if(i>0 && !type1Array[i].equals(type2Array[i-1])){
int trackStop = i;
for(int j = trackStart; j<trackStop;j++){
type2.add(type2Array[j]);
}
type1_type2.put(type1Array[i-1], type2);
list_type1_type2.add(type1_type2);
//debugging stuff
String x = list_type1_type2.toString();
System.out.println(x);
System.out.println(" printing because "+ type1Array[i]+" is not equal to " + type1Array[i-1]);
type2 = new ArrayList<String>();
type1_type2 = new HashMap<String,List<String>>();
trackStart=i;
}
i++;
}
当结果对象的最后一个type1值相同时,此方法不起作用。
有没有办法以同样的精神(在 while(res.next) 内)做到这一点,而无需先将数据库调用的结果存储在单独的数组中,或者在 while 循环之外添加一个额外的 for 循环来“修补它起来”?
【问题讨论】:
-
Ugg 真的很难阅读代码。我会认真考虑重构以避免使用 field1、field2 等类型的变量命名。这让事情真的很难理解。其次,您是否考虑过使用集合类而不是数组是否可以更好地编写代码?它通常会使事情变得简单得多。
-
只是一个提示:当你必须嵌套 Collection 类时,这通常表明你应该创建一个新类来包含所有内容,否则组织行为将变得非常乏味并且会犯愚蠢的错误。
标签: java database arrays data-structures hashmap