如何从java中的方法返回Integer或int和列表? [英] How to return an Integer or int and a list from a method in java?

查看:569
本文介绍了如何从java中的方法返回Integer或int和列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从类中的方法返回一个int和一个列表。但我不能成为那个班级的对象。所以我应该怎么做。

I am trying to return an int and a list from a method from a class. but i cant make object of that class. so how should i do it.

我尝试这样做:

        List listofObj = new ArrayList();
        List list1 = some code that i can't share;
        Integer total = some integer value;

        listOfObj.add((List) list1 );
        listOfObj.add((Integer) total);

        return listofObj;

但是当我在另一个班级使用它时 -

but when i use it in another class -

        if (listOfObj != null && listOfObj.size() > 0) {

            List mainList = promoData.get(0); --- gives error
        count = (Integer) promoData.get(1);
        }

所以我试过这个---

so i tried this ---

        if (listOfObj != null && listOfObj.size() > 0) {
            Map promoData = (Map) listOfObj;
            List mainList = (List) promoData.get(0);
            count = (Integer) promoData.get(1);
        }

但是当我点击应用程序时它仍会出错。

but it still gives error when i hit the application.

错误:java.lang.ClassCastException:java.util.ArrayList无法强制转换为java.util.Map

error : java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map

推荐答案

你可以使用一对类

public class Pair<X,Y> {
   public final X first;
   public final Y second;

   public Pair(X first, Y second) { this.first = first; this.second = second; }

   public static<XX,YY> of(XX xx, YY yy) { return new Pair<XX,YY>(xx, yy); }
}

然后按如下方式定义您的方法:

Then define your method as follows:

 public Pair<List, Integer> myMethod() { 
    List someList = ...;
    int someInt = ....;
    ...
    return Pair.of(someList, someInt); 
 }

在来电方:

Pair<List, Integer> pair = myMethod();
List mainList = pair.first;
int count = pair.second;

如果你有 Guava 库你可以从那里使用Pair类。

If you have the Guava library you can use a Pair class from there.

如果你想使用地图,你将不得不对其价值进行贬低:

If you want to use a map, you will have to do a downcast on its values:

public Map<String, Object> myMethod() { 
  List someList = ...;
  int someInt = ....;
  ...
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("list", someList);
  map.put("count", someInt);
  return map;
}

在来电方:

Map<String, Object> map = myMethod();
List mainList = (List) map.get("list");
int count = (Integer) map.get("count");

这篇关于如何从java中的方法返回Integer或int和列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆