Can ArrayList store different objects?
Using generic, ArrayList class can be used to store any type of object. In other words, we can store multiple types of objects in an ArrayList using generic feature. For example, we could have an ArrayList of Book objects, an ArrayList of Employee objects, or an ArrayList of Strings.
Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null . Elements in the ArrayList are accessed via an integer index.
Since ArrayList in Java is backed by a built-in array, the limit on the size is equal the same as the limit on the size of an array, i.e. 2147483647. Since your project is for android platform, you would run out of memory before reaching this limit. However, 8000 is a relatively small number.
A list can only hold the items of the datatype of its declared datatype. We can declare a list of datatype Object and store items of different datatype.
ArrayLists cannot hold primitive data types such as int, double, char, and long (they can hold String since String is an object, and wrapper class objects (Double, Integer).
Indeed, you can store a number, a string, and even another list within a single list.
- List<Integer> anotherList = Arrays. asList(5, 12, 9, 3, 15, 88); list. ...
- List<Integer> list = new ArrayList<>(); Collections. addAll(list, 1, 2, 3, 4, 5);
- List<Integer> list = new ArrayList<>(); Integer[] otherList = new Integer[] {1, 2, 3, 4, 5}; Collections.
The ArrayList class is a Java class that you can use to store lists of objects. You can also store objects in an array, but arrays have a couple of obvious problems. To create an array, you have to specify a size for the array.
Yes, you can store objects of different types in an ArrayList but, like pst mentioned, it's a pain to deal with them later. If the values are related in some way you are probably better off writing a class to hold them.
Add Objects of Different Types in an ArrayList
In Java, ArrayList can hold objects of wrapper classes like double, integer, and string. We then add elements to the ArrayList using the add() method. Firstly, we added a string value to our ArrayList , then a double value, integer, and float, respectively.