Java对象上的不兼容类型

时间:2019-10-01 04:22:17

标签: java

即使元素类型是Double,编译器也不喜欢将对象中的元素分配给变量类型Double。我想念什么?

Object relWeights [][] = new Object[2][];
relWeights[0] = new String [] {
    "Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"
};
relWeights[1] = new Double [] {
    0.78, 0.39, 2.65, 1.17, 1.05, 1.23
};
Double temp = relWeights[1][planetVisiting-1];
//compiler faults here with incompatible types

System.out.println("Your weight on " + relWeights[0][planetVisiting-1] + " is " + temp*weightOnEarth +"pounds");
}

2 个答案:

答案 0 :(得分:2)

@SSP建议的解决方案很好地描述了该问题:编译器仅知道您的条目的类型为Object。需要进行类型转换以告知编译器它是double

对于推断的用例,我建议使用Map而不是数组。基本解决方案会有所不同。

Map<String, Double> relWeights = new HashMap();
relWeights.put("Venus", 0.78);
relWeights.put("Mars", 0.39);
relWeights.put("Jupiter", 2.65);
relWeights.put("Saturn", 1.17);
relWeights.put("Uranus", 1.05);
relWeights.put("Neptune", 1.23);

Map是键值存储。它为每个键分配一个值。可以说relWeights.get("specific_key")来获得分配给该键的值(在本示例中,分配给Double的{​​{1}})。

String

但是,如果您需要按数字输入,请务必注意未订购String planet = "Jupiter"; double temp = relWeights.get(planet); double weightOnEarth = 38.62; System.out.println("Your weight on " + selectedPlanet + " is " + temp*weightOnEarth + "pounds"); 。在这种情况下,应使用HashMap,并且需要按位置检索时,将值转换为LinkedHashMap

ArrayList

答案 1 :(得分:1)

如果出于任何目的将Object类用作类型,然后要将数据转换为其自己的类型。您需要像下面这样投射数据:-

Object relWeights [][] = new Object[2][];
relWeights[0] = new String [] {"Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
relWeights[1] = new Double [] {0.78, 0.39, 2.65, 1.17, 1.05, 1.23} ;
Double temp = (Double)relWeights[1][planetVisiting-1];