簡體   English   中英

如何將Integer添加到ArrayList <Float>

[英]How to add Integer to ArrayList<Float>

我想將Integer添加到Float類型的類型安全ArrayList中。

Float a = new Float(1.1);
ArrayList<Float> obj = new ArrayList<Float>();
obj.add(a);//In the obj object I want to add integer. how can I do that?
Integer b = new Integer(1);
obj.add(b);/*The method add(Float) in the type ArrayList<Float> 
                is not applicable for the arguments (Integer)*/

將ArrayList的類型更改為: ArrayList<Number>

因為NumberFloatInteger的基類。 因此,您可以將它們都存儲在列表中。

或將您的Integer轉換為Floatobj.add(Float.valueOf(b));

嘗試這個

obj.add((float) b);

得到integerfloat

要么

obj.add(Float.parseInt(b));

您不能像這樣指定ArrayList的類型:

    Float a = new Float(1.1);
    ArrayList<Float> obj = new ArrayList<Float>();
    obj.add(a);//In the obj object i want to add integer how can i do that
    Integer b = new Integer(1);
    ArrayList newobj = (ArrayList) obj;
    newobj.add(b);

    for (Object object : newobj) {
        System.out.println(object.getClass());
    }

將輸出:

class java.lang.Float
class java.lang.Integer

或者您可以使用ArrayList<Number>

    Float a = new Float(1.1);
    ArrayList<Number> obj = new ArrayList<Number>();
    obj.add(a);//In the obj object i want to add integer how can i do that
    Integer b = new Integer(1);

    obj.add(b);

    for (Number object : obj) {
        System.out.println(object.getClass());
    }

將輸出:

class java.lang.Float
class java.lang.Integer

關於什么

obj.add(b.floatValue());

或使用ArrayList<Number>

這就是我最終在不更改ArrayList類型的情況下添加Integer的方式,但是生成了警告

public class MyArrayList{
public static void main(String[] args) {
    Float a = new Float(1.1);
    ArrayList<Float> obj = new ArrayList<Float>();
    obj.add(a);
    function1(obj);
    for (Object obj2 : obj) {
        System.out.println(obj2);
    }
}
private static void function1(ArrayList list) {
    Integer b = new Integer(1);
    list.add(b);
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM