Create an ArrayList with multiple object types?
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.
Solution 1:
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.
Solution 2:
(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);
Solution 3:
You can use Object for storing any type of value for e.g. int, float, String, class objects, or any other java objects, since it is the root of all the class. For e.g.
-
Declaring a class
class Person { public int personId; public String personName; public int getPersonId() { return personId; } public void setPersonId(int personId) { this.personId = personId; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; }}
-
main function code, which creates the new person object, int, float, and string type, and then is added to the List, and iterated using for loop. Each object is identified, and then the value is printed.
Person p = new Person(); p.setPersonId(1); p.setPersonName("Tom"); List<Object> lstObject = new ArrayList<Object>(); lstObject.add(1232); lstObject.add("String"); lstObject.add(122.212f); lstObject.add(p); for (Object obj : lstObject) { if (obj.getClass() == String.class) { System.out.println("I found a string :- " + obj); } if (obj.getClass() == Integer.class) { System.out.println("I found an int :- " + obj); } if (obj.getClass() == Float.class) { System.out.println("I found a float :- " + obj); } if (obj.getClass() == Person.class) { Person person = (Person) obj; System.out.println("I found a person object"); System.out.println("Person Id :- " + person.getPersonId()); System.out.println("Person Name :- " + person.getPersonName()); } }
You can find more information on the object class on this link Object in java
Solution 4:
List<Object> list = new ArrayList<>();
list.add(1);
list.add("1");
As the return type of ArrayList is object, you can add any type of data to ArrayList but it is not a good practice to use ArrayList because there is unnecessary boxing and unboxing.