Arraylist containing Integers and Strings
List<Object> oList=new ArrayList<Object>();
If it's avoidable, please avoid this list of Object type. Go for individual lists.
If not then you should go for type of Object
List<Object> list = new ArrayList<Object>();
which accept all the type Objects, but have to take care while retrieving.
Checking the objects while retrieving
for (Object obj: list) {
if (obj instanceof String){
// this is string
} else if (obj instanceof Integer) {
// this is Integer
}
}
You can use tagged sum types: Either<A, B>
is either Left<A, B>
or Right<A, B>
. In Java it will look like:
public interface Either<A, B>;
public class Left<A, B> implements Either<A, B> {
public final A value;
public Left(A value) {
this.value = value;
}
}
public class Right<A, B> implements Either<A, B> {
public final B value;
public Right(B value) {
this.value = value;
}
}
So, you can use ArrayList<Either<Integer, String>>
.
for (Either<Integer, String> either : intsOrStrings) {
if (either instanceof Left) {
Integer i = ((Left<Integer, String>) either).value;
} else if (either instanceof Right) {
String s = ((Right<Integer, String>) either).value;
}
}
This approach is more type-safe than using Object
.
You can do this as follows but have to give up on generics for the list container.
List<List> listOfMixedTypes = new ArrayList<List>();
ArrayList<String> listOfStrings = new ArrayList<String>();
ArrayList<Integer> listOfIntegers = new ArrayList<Integer>();
listOfMixedTypes.add(listOfStrings);
listOfMixedTypes.add(listOfIntegers);
But, a better way would be to use a Map
to keep track of the two lists since the compiler would no longer be able to prevent you from mixing types like putting a String into an Integer list.
Map<String, List> mapOfLists = new HashMap<String, List>();
mapOfLists.put("strings", listOfStrings);
mapOfLists.put("integers", listOfIntegers);
mapOfLists.get("strings").add("value");
mapOfLists.get("integers").add(new Integer(10));