[英]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>
。
因为Number
是Float
和Integer
的基类。 因此,您可以将它们都存储在列表中。
或将您的Integer
转换为Float
值obj.add(Float.valueOf(b));
尝试这个
obj.add((float) b);
得到integer
的float
要么
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.