Arraylist containing Integers and Strings

arraylist, generics, java

Solution

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));

Problem

I want to create a Arraylist which should contain Integers and Strings.. Is that possible? I have created two Arraylist as given below: ``` ArrayList<Integer> intList=new ArrayList<Integer>(); intList.add(1); intList.add(2); ArrayList<String> strList=new ArrayList<String>(); strList.add("India"); strList.add("USA"); strList.add("Canada"); ``` I want to put intList & strList into a new ArrayList. Can I do that?? If so, How??

Original source