问题
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.
i try to do this :
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.
error : java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
回答1:
You can use a pair class
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);
}
In the caller side:
Pair<List, Integer> pair = myMethod();
List mainList = pair.first;
int count = pair.second;
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;
}
In the caller side:
Map<String, Object> map = myMethod();
List mainList = (List) map.get("list");
int count = (Integer) map.get("count");
回答2:
A possible simple solution would be to create a class that has int and List<T> members and return an instance of that class.
Possibly relevant: What is the equivalent of the C++ Pair<L,R> in Java? for example implementations of a generic pair class.
回答3:
There are several possibilities:
First you can create a class containing a List and the int.
The next possibility is to return an Object[]. The disadvantage of this is that you lose the type safety.
The third possibility is to provide the list into the method call and fill it there and only return the int.
回答4:
Two solutions that came into my mind:
- Make a class that has an int and an ArrayList and return an instance of that class. I would recommend this.
- Initialize the ArrayList outside of your method and send it as a parameter. The method has to return only the int value because the changes made to the ArrayList will be seen outside of your method.
来源:https://stackoverflow.com/questions/17830949/how-to-return-an-integer-or-int-and-a-list-from-a-method-in-java