我有一个
Object obj
包括混合类型的数组。例如,
System.out.println(obj.toString); //prints [4.3,3,size]
我需要将{4.3}作为double
,将“3”作为int
,将“尺寸”作为String
。
这应该有效:
if (FirstElementOfobj instanceof String){
System.out.println("String! "+ FirstElementOfobj+" works");
} else if (FirstElementOfobj instanceof Integer) {
System.out.println("Int! Adding 2 "+ FirstElementOfobj+2);
} else if (FirstElementOfobj instanceof Double) {
System.out.println("Double! Adding 3.0"+ FirstElementOfobj+3.0);
}
但它不是因为
System.out.println(obj.getClass()); // prints class java.util.ArrayList
所以我认为我需要以某种方式分解对象...我想,如果它是ArrayList
,那么是不是应该有类似obj[0]
的东西来访问第一个元素?
编辑:
我的问题的解决方案是
double myDouble = (double) ((ArrayList) obj).get(0);
答案 0 :(得分:2)
如果obj
包含List
个实例,请将其转换为List
:
if (obj instance of List) {
List list = (List) obj;
for (Object o : list) {
if (o instanceof Whatever) {
Whatever w = (Whatever) o;
}
}
}
答案 1 :(得分:0)
Please try this code ,
I have create an Arraylist with different object types
and print the result you want you need to cast to Object to get
each object type inside the array list
public static void main (String args[])
{
List myList = new ArrayList();
myList.add("StringValue");
myList.add(3.5);
myList.add(3);
for(int i = 0 ; i < myList.size();i++){
System.out.println((Object)myList.get(i).getClass());
}
}
and there is the output
class java.lang.String
class java.lang.Double
class java.lang.Integer