我使用一種方法從數(shù)據(jù)庫中獲取數(shù)據(jù)并將其存儲在向量中。該方法將始終返回一個 Vector of Objects,其中 Object 數(shù)據(jù)類型可以是 Date、Double 或 String。就我而言,我知道我得到的是 Double,但我想將其轉(zhuǎn)換為 int。有沒有比以下更簡單的方法:System.out.println((int)Double.parseDouble(vector1.get(1).toString()));我嘗試過的其他方法無效:System.out.println((Integer)vector1.get(1)); // java.lang.ClassCastException: java.lang.Double incompatible with java.lang.IntegerSystem.out.println((int)vector1.get(1));在此先感謝您的任何建設(shè)性回應(yīng)
3 回答

慕后森
TA貢獻1802條經(jīng)驗 獲得超5個贊
按照這個答案,我們可以將代碼轉(zhuǎn)換為
Double d = vector1.get(1); Integer i = d.intValue();
我在這里假設(shè),如果你有一些數(shù)組,也許你想將那里的所有數(shù)據(jù)轉(zhuǎn)換Double
成Integer
vector1.stream().mapToInt(n -> n.intValue()).mapToObj(Integer::new).collect(Collectors.toList());
或者
vector1.stream().mapToInt(Double::intValue).mapToObj(Integer::new).collect(Collectors.toList());

眼眸繁星
TA貢獻1873條經(jīng)驗 獲得超9個贊
您可以使用 Math.round(double) 獲取 int 值。作為
雙 d = Double.parseDouble(vector1.get(1));
int v = (int) Math.round(d);

絕地?zé)o雙
TA貢獻1946條經(jīng)驗 獲得超4個贊
您可以使用 intValue() 來獲取 int 值。
Double b = new Double((double)vector1.get(1)); int value = b.intValue();
添加回答
舉報
0/150
提交
取消