Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an ArrayList with multiple object types?

Tags:

java

arraylist

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.

like image 962
Dakshila Kamalsooriya Avatar asked Oct 26 '13 03:10

Dakshila Kamalsooriya


People also ask

Can ArrayList hold multiple object types?

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.

Can an ArrayList have different data types?

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

Can you add multiple elements to an ArrayList at once?

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.


2 Answers

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.

like image 77
Crickcoder Avatar answered Nov 10 '22 09:11

Crickcoder


(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); 
like image 36
Darshana Ekanayake Avatar answered Nov 10 '22 10:11

Darshana Ekanayake