How do I create an ArrayList
with integer and string input types? If I create one as:
List<Integer> sections = new ArrayList <Integer>();
that will be an Integer
type ArrayList
. If I create one as:
List<String> sections = new ArrayList <String>();
that will be of String
type. How can I create an ArrayList
which can take both integer and string input types? Thank you.
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. We will discuss how we can use the Object class to create an ArrayList. Object class is the root of the class hierarchy.
ArrayList cannot hold primitive data types such as int, double, char, and long. With the introduction to wrapped class in java that was created to hold primitive data values. Objects of these types hold one value of their corresponding primitive type(int, double, short, byte).
To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using Arrays. asList(), and passing the List to the ArrayList constructor. In the given example, we are adding two strings “a” and “b” to the ArrayList.
You can make it like :
List<Object> sections = new ArrayList <Object>();
(Recommended) Another possible solution would be to make a custom model class with two parameters one Integer and other String. Then using an ArrayList
of that object.
(1)
ArrayList<Object> list = new ArrayList <>();` list.add("ddd"); list.add(2); list.add(11122.33); System.out.println(list);
(2)
ArrayList arraylist = new ArrayList(); arraylist.add(5); arraylist.add("saman"); arraylist.add(4.3); System.out.println(arraylist);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With