G
grz01
... The code you wrote made my eyes bleed ...
OK, Mark, since I dont want to
risk anyones physical wellbeing
I'll re-phrase the question
(starting from scratch with a new thread).
The problem I started out with was from a real programming task.
I wanted to make a static function
that returns a Pair of Lists,
where the first component
(lets say, for simplicity)
is known to be: List<Integer>
and the other component is: List<String>
So the return-type really should be:
Pair<List<Integer>,List<String>>
But since I dont think Java has any type for Pair<A,B> (?) and I dont
like to create yet another custom-class only for this trivial purpose,
I decided instead to try a return-type like either
List<List<Object>> or
List<List<?>>
where the "returnvalue.get(0)" is of type List<Integer>
and "returnvalue.get(1)" is of type List<String>
(is there a better candidate for a return-type, without creating a new
class?)
Now, if I try:
public static List<List<Object>> returnListList() {
List<List<Object>> result = new ArrayList<List<Object>>();
List<Integer> iList = new ArrayList<Integer>();
// ... add some objects to iList...
List<String> sList = new ArrayList<String>();
// ... add some objects to sList...
result.add(iList);
result.add(sList);
return result;
}
the .add() method-calls give a type-error.
And it also does *not* work to try this instead:
result.add((List<Object>)iList);
result.add((List<Object>)sList);
Of course, I could declare iList and sList as List<Object> instead,
but I would really like to keep the type-info there, for clarity.
After some experimentation, I found this one *does* works:
public static List<List<?>> returnListList01() {
List<List<?>> result = new ArrayList<List<?>>();
List<Integer> iList = new ArrayList<Integer>();
// ... add some objects to iList...
List<String> sList = new ArrayList<String>();
// ... add some objects to sList...
result.add(iList);
result.add(sList);
return result;
}
But unfortunately, the last function gives me a problem when I try to
*consume* it, and extract the two lists from the returnvalue.
If I do
public static void consume(){
List<List<?>> myList = returnListList();
List<Integer> iList = (List<Integer>)myList.get(0);
List<String> sList = (List<String>)myList.get(0);
}
I again get the warning:
Type safety: Unchecked cast from List<capture#1-of ?> to
List<Integer>
And I dont seem to be able to rewrite it, without getting some other
error or warning.
Any hints, what is the best way to do what I want to achieve? I.e
return a pair of lists of known, but different types (without
creating a new class) and then split the returnvalue into the two
separate lists?
/ grz01