How to return an Integer or int and a list from a method in java? -
i trying return int , list method class. cant make object of class. how should it.
i try :
list listofobj = new arraylist(); list list1 = code can't share; integer total = integer value; listofobj.add((list) list1 ); listofobj.add((integer) total); return listofobj;
but when use in class -
if (listofobj != null && listofobj.size() > 0) { list mainlist = promodata.get(0); --- gives error count = (integer) promodata.get(1); }
so tried ---
if (listofobj != null && listofobj.size() > 0) { map promodata = (map) listofobj; list mainlist = (list) promodata.get(0); count = (integer) promodata.get(1); }
but still gives error when hit application.
error : java.lang.classcastexception: java.util.arraylist cannot cast java.util.map
you can use 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 method follows:
public pair<list, integer> mymethod() { list somelist = ...; int someint = ....; ... return pair.of(somelist, someint); }
in caller side:
pair<list, integer> pair = mymethod(); list mainlist = pair.first; int count = pair.second;
if have guava library can use pair class there.
if want use map, have downcast on 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 caller side:
map<string, object> map = mymethod(); list mainlist = (list) map.get("list"); int count = (integer) map.get("count");
Comments
Post a Comment