I have an ArrayList with multiple objects of different types. At one index I have an element with a String value. I know the index location and I know the string is associated with either a integer or double value.
How do I check if the value that object is associated with is a double or an integer?
EDIT: It's not that I'm trying to compare 5.5 to 5, when I try to check the data type of either object, I get a compiler error stating I can't parse an object.
My arraylist is comprised of two String objects. What I'm doing is parsing the String object rather than the String value associated with the object.
EDIT2: Correction!!! The objects are in fact NOT String objects. Instead, they are just objects with no specific class associated with them. Without declaring an object type in your arraylist, the arraylist will automatically assign every element to an object value (rather than one object being a String, one object being a double, one object being an int, etc.)
~~~
Example of my code:
import java.util.ArrayList;
public class idk {
public static void main(String[] args) {
ArrayList myList1 = new ArrayList();
ArrayList myList2 = new ArrayList();
myList1.add("5.5");
myList2.add("5");
//How does one check if the value associated to the String object
//in the arrayList (like myList.get(1)) is a double or an integer?
}
}
I've only tried implementing an isDouble method but its checking if the object is a double rather than the value of the string object.
import java.util.ArrayList;
public class idk {
//I've attempted to try using this method to check the value but I get
//a compiler error saying I can't use the isDouble method which checks
//for a String value, not the value of the actual String object in the arraylist
boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
public static void main(String[] args) {
ArrayList myList1 = new ArrayList();
ArrayList myList2 = new ArrayList();
myList1.add("5.5");
myList2.add("5");
if (isDouble(myList1.get(0))==true) {
System.out.println("The object in pos 0 is a double");
}else {
System.out.println("The object in pos 0 is not a double");
}
if (isDouble(myList1.get(0))==true) {
System.out.println("The object in pos 0 is a double");
}else {
System.out.println("The object in pos 0 is not a double");
}
}