you can not specify the type of the ArrayList like :
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());
}
Would output:
class java.lang.Float
class java.lang.Integer
Or you can Use an 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());
}
Would output:
class java.lang.Float
class java.lang.Integer
Floatcan only, logically, contain Floats. Luckily both integers and floats are numbers so it's not too hard to convert an integer to a float.