Newsletter |
How to Store Multiple Data types In An ArrayList
Core Java » on Feb 21, 2014 { 8 Comments } By Sivateja
So, how to store objects of multiple data types in the ArrayList, in fact storing is pretty simple, every one will get some idea but how to retrieve the values ? for example if we have 100+ values in the ArrayList object of different types then ? let us see how to do handle that situation.
Example : ArrayList with Multiple Data Types
import java.util.ArrayList; import java.util.List; public class ArrayLst { public static void main(String... args) { ArrayList al = new ArrayList(); al.add("Java4s"); al.add(12); al.add(12.54f); for(int i=0;i<al.size();i++) { Object o = al.get(i); if(o instanceof String || o instanceof Float || o instanceof Integer) System.out.println("Value is "+o.toString()); } } }
Output
Value is Java4s
Value is 12
Value is 12.54
Explanation
In the above application, we can print the values by converting our ArrayList object into the Array [ al.toArray() ] also, but in the real time, there may be a chance to add some user defined class objects into the ArrayList, in that scenario obviously the better approach will be converting to Object type and then check the type caste and go ahead.
You Might Also Like
::. About the Author .:: | ||
Comments
8 Responses to “How to Store Multiple Data types In An ArrayList”
How about if you add an Arraylist of String in al. How do you print it out?
Thanks.
Why a raw type and not just use ArrayList ?! Why all the instanceof, when they all must be Objects and all have toString()? I don’t see what there is to learn from this “how to”.
Hi, awesome website.
if we store null in the above arraylist object then we get exception in above program… Am I correct
Hi All,
It depends on what type of data you store in ArrayList. So accordingly we have to check all object types in ‘IF’ condition before printing.
The above program is just an example only, this can be customized.
Well explained article.
I was searching for the solution and here i found one.
Thanks once again.
Hi,
Good Explanation….can i know that how to use foreach loop for above problem.
can someone post another example of arrraylist and linkedlist.
Great post. Love the pictures. Colourful yet subtle.