How to get ArrayList<String> to ArrayList<Object> and vice versa in java?



ArrayList<String> to ArrayList<Object>

Instead of the typed parameter in generics (T) you can also use “?”, representing an unknown type. These are known as wild cards you can use a wild card as − Type of parameter or, a Field or, a Local field. Using wild cards, you can convert ArrayList<String> to ArrayList<Object> as −

ArrayList<String> stringList = (ArrayList<String>)(ArrayList<?>)(list);

Example

Open Compiler
import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class ArrayListExample { public static void main(String args[]) { //Instantiating an ArrayList object ArrayList<Object> list = new ArrayList<Object>(); //populating the ArrayList list.add("apples"); list.add("mangoes"); list.add("oranges"); //Converting the Array list of object type into String type ArrayList<String> stringList = (ArrayList<String>)(ArrayList<?>)(list); //listing the contenmts of the obtained list Iterator<String> it = stringList.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }

Output

apples
mangoes
oranges

ArrayList<Object> to ArrayList<String>

To convert the ArrayList<Object> to ArrayList<String> −

  • Create/Get an ArrayList object of String type.

  • Create a new ArrayList object of Object type by passing the above obtained/created object as a parameter to its constructor.

Example

Open Compiler
import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class ArrayListExample { public static void main(String args[]) { //Instantiating an ArrayList object ArrayList<String> stringList = new ArrayList<String>(); //populating the ArrayList stringList.add("apples"); stringList.add("mangoes"); stringList.add("oranges"); //Converting the Array list of String type to object type ArrayList<Object> objectList = new ArrayList<Object>(stringList); //listing the contents of the obtained list Iterator<String> it = stringList.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }

Output

apples
mangoes
oranges
Updated on: 2024-06-07T10:28:55+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements