java中return返回多个值或者多种类型的值的方法(list;Map) 您所在的位置:网站首页 函数返回多个值以什么类型保存 java中return返回多个值或者多种类型的值的方法(list;Map)

java中return返回多个值或者多种类型的值的方法(list;Map)

2024-04-08 15:06| 来源: 网络整理| 查看: 265

java中return返回多个值或者多种类型的值的方法(list;Map)

1.在写方法的时候,有时候需要返回多个值,有时候返回的多个值的类型还不同,依据不同情况以下提供了三种方法返回多个值。

2.具体思路都在代码注释里了。如果返回的多个值类型相同,可以用方法一和方法二;如果返回的多个值类型不同,可以用方法三。

初试写作,略感激动。

import java.util.*; public class Demo { //方法1:返回list public static List returnList(){ List list=new ArrayList(); list.add(new int[]{1}); list.add(new int[]{1, 2}); list.add(new int[]{1, 2, 3}); return list; } //方法2:返回Map,一个Map只能有一种数据类型 public static Map returnMap(){ Map map = new HashMap(); map.put("age",1); //”age“是key,类似于索引,1是索引对应的int值 map.put("high",30); //System.out.println(map.get("age")); Map map1 = new HashMap(); map1.put("array", new int[]{1, 2, 3}); //System.out.println(Arrays.toString( map1.get("array") )); return map; } //方法3:一次性返回两种类型的数据,结合了Map和list public static List returnMapList(){ Map map = new HashMap(); map.put("age",1); map.put("high",30); Map map1 = new HashMap(); map1.put("array", new int[]{1, 2}); List listMap = new ArrayList(); listMap.add(map); listMap.add(map1); return listMap; } //测试代码 public static void main(String[] args){ //返回list List list1 = returnList(); System.out.println(Arrays.toString(list1.get(0)) + Arrays.toString(list1.get(1)) + Arrays.toString(list1.get(2)) + "\nreturnlist结束\n"); //返回Map,一个Map只能有一种数据类型 Map mapTest = returnMap(); System.out.println("age = " + mapTest.get("age") +", high = " + mapTest.get("high") + "\nreturnMap结束\n"); //一次性返回两种类型的数据,结合了Map和list List list2 = returnMapList(); System.out.println(list2.get(0) +" , " + list2.get(1) + "\nreturnMapList结束");//list2.get(1)是数组的地址 System.out.print("调用返回的int和int[]:"); Map map0 = list2.get(0); Map map1 = list2.get(1); System.out.println( "age = " + map0.get("age") ); System.out.println("array = " + Arrays.toString((int[]) map1.get("array"))); // System.out.println(Arrays.toString((int[]) list2.get(1).get("array"))); //调用过程也可以这样写 } }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有