Re: Java type-casting -- Q3
grz01 wrote:
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?
I agree with Lew. Make a public Pair class static inside your class,
and then just return that type. Once you do that the problem becomes
easy. If you really need to manipulate types that are totally unknown,
it's possible, but rather tricky to get right, and never faster than the
type safe code.
My IDE wrote the entire Pair class for me, btw, except for the first
three lines.
Note that there's no casts (and no warnings) anywhere in this code.
package fubar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyStuff {
public static void main( String[] args )
{
Pair<List<Integer>,List<String>> lists = makeLists();
consume( lists.getFirst() );
consume( lists.getSecond() );
}
public static class Pair<A,B> {
private final A first;
private final B second;
public Pair( A first, B second )
{
this.first = first;
this.second = second;
}
public A getFirst()
{
return first;
}
public B getSecond()
{
return second;
}
}
public static Pair<List<Integer>,List<String>> makeLists() {
List<Integer> intList = new ArrayList<Integer>(
Arrays.asList( 1, 2, 3 ) );
List<String> strList = new ArrayList<String>(
Arrays.asList( "a","b","c" ) );
return new Pair<List<Integer>,List<String>>( intList, strList );
}
public static void consume( List<?> list ) {
for( Object o : list ) {
System.out.println( o );
}
}
}