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