Bounding ArrayList
by , 11-13-2011 at 11:45 AM (707 Views)
Collections can be of a particular type i.e they are only allowed to hold objects of a defined type. This is called “bounded by”. For example:
Java Code:ArrayList arrayList = new ArrayList(); Vector vector = new Vector();
We declared an ArrayList and a Vector both bounded by String. We cannot store objects other than String in these. Lets try to store an integer in Vector and see what happens.
Exception:Java Code:Vector vector = new Vector(); vector.add(1);
The method add(int, String) in the type Vector
is not applicable for the arguments (int)
So it makes sense. We have more control over collections if we bind them with a type.
Now lets take another example:
ParentClass.java
To make the example more interesting, lets take another class ClassC which does not inherit from ParentClass.Java Code:public class ParentClass { private int a; private String b; public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } } ClassA and ClassB inherit from ParentClass. ClassA.java public class ClassA extends ParentClass { private String x; public String getX() { return x; } public void setX(String x) { this.x = x; } } ClassB.java public class ClassB { private String y; public String getY() { return y; } public void setY(String y) { this.y = y; } }
ClassC.java
Now lets do some experiments.Java Code:public class ClassC { private String z; public String getZ() { return z; } public void setZ(String z) { this.z = z; } }
Above code works perfectly fine. ArrayList is bounded by ParentClass and we tried to store objects of ParentClass and ClassA, ClassB and ClassC, which are Childs of ParentClass. So this means, that we can store objects of classes that extend the class with which the ArrayList is bounded.Java Code:ArrayList arrayList = new ArrayList(); ParentClass objp = new ParentClass(); ClassA obja = new ClassA(); ClassB objb = new ClassB(); arrayList.add(objp); arrayList.add(obja); arrayList.add(objb);
Now lets try something interesting. Lets try to store object of class ClassC (which is not subclass of ParentClass) in the arraylist.
Exception:Java Code:ArrayList arrayList = new ArrayList(); ClassC objc = new ClassC(); arrayList.add(objc);
The method add(ParentClass) in the type ArrayList is not
applicable for the arguments (ClassC)
So, you can only store objects of the class(even the children of that class) with which the collection is bounded by.









Email Blog Entry
Size Reduced for Images in PDF &...
05-15-2013, 05:53 PM in Java Software