javalists
① java中如何返回多個list
方法一、將多個List封裝到一個JavaBean內:
private static void show1() {
StringEQTest.ListArr listArr = new StringEQTest.ListArr();
List<String> names = listArr.names;
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
List<Integer> ages = listArr.ages;
for (int i = 0; i < ages.size(); i++) {
System.out.println(ages.get(i));
}
}
public static class ListArr {
List<String> names = new ArrayList<String>();
List<Integer> ages = new ArrayList<Integer>();
public ListArr() {
names.add("names1");
names.add("names2");
names.add("names3");
ages.add(50);
ages.add(40);
ages.add(30);
ages.add(88);
}
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public List<Integer> getAges() {
return ages;
}
public void setAges(List<Integer> ages) {
this.ages = ages;
}
}
結果:
names1
names2
names3
50
40
30
88
-------------------------------------------------------------------------------
方法二、將List包裝到Map集合內,取出的時候需要進行類型轉換
private static void show2() {
Map<String, Object> lists = getLists();
List<String> names = (List<String>) lists.get("names");
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
List<Integer> ages = (List<Integer>) lists.get("ages");
for (int i = 0; i < ages.size(); i++) {
System.out.println(ages.get(i));
}
}
public static Map<String, Object> getLists() {
List<String> names = new ArrayList<String>();
List<Integer> ages = new ArrayList<Integer>();
names.add("names1");
names.add("names2");
names.add("names3");
ages.add(50);
ages.add(40);
ages.add(30);
ages.add(88);
Map<String, Object> map = new HashMap<String, Object>();
map.put("names", names);
map.put("ages", ages);
return map;
}
結果:
names1
names2
names3
50
40
30
88