Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out what type each object is in a ArrayList<Object>?

I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?

FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.

like image 516
WolfmanDragon Avatar asked Sep 19 '08 23:09

WolfmanDragon


People also ask

How do you find the type of an ArrayList?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.

How do you check what type an object is?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.

Can ArrayList contain different object 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).

How do you check if an object is in an ArrayList?

ArrayList. contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.


1 Answers

In C#:
Fixed with recommendation from Mike

ArrayList list = ...; // List<object> list = ...; foreach (object o in list) {     if (o is int) {         HandleInt((int)o);     }     else if (o is string) {         HandleString((string)o);     }     ... } 

In Java:

ArrayList<Object> list = ...; for (Object o : list) {     if (o instanceof Integer)) {         handleInt((Integer o).intValue());     }     else if (o instanceof String)) {         handleString((String)o);     }     ... } 
like image 194
Frank Krueger Avatar answered Oct 13 '22 05:10

Frank Krueger