【发布时间】:2016-05-13 07:19:28
【问题描述】:
我有一个包含多个不同类型对象的 ArrayList。 在一个索引处,我有一个带有 String 值的元素。我知道索引位置,并且我知道字符串与整数或双精度值相关联。
如何检查对象关联的值是双精度还是整数?
编辑:我不是在尝试将 5.5 与 5 进行比较,当我尝试检查任一 object 的数据类型时,我得到一个编译器错误说明我无法解析对象。
我的数组列表由两个字符串对象组成。我正在做的是解析 String 对象,而不是与该对象关联的String 值。
EDIT2:更正!!!这些对象实际上是NOT String 对象。相反,它们只是没有与它们关联的特定类的对象。无需在数组列表中声明对象类型,数组列表将自动将每个元素分配给一个对象值(而不是一个对象是 String,一个对象是 double,一个对象是 int,等等)
~~~
我的代码示例:
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?
}
}
我只尝试过实现 isDouble 方法,但它会检查对象是否为 double 而不是字符串对象的值。
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");
}
}
【问题讨论】:
-
您已经实现了 isDouble 似乎工作正常。你还需要补充什么?
标签: java string object arraylist