Bounding ArrayList
3 December 2007Collections 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:
ArrayList <String> arrayList = new ArrayList<String>(); Vector <String> vector = new Vector<String>();
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.
Vector <String> vector = new Vector<String>(); vector.add(1);
Exception:
The method add(int, String) in the type Vector<String> 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
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; } }
To make the example more interesting, lets take another calss ClassC which does not inherit from ParentClass.
ClassC.java
public class ClassC { private String z; public String getZ() { return z; } public void setZ(String z) { this.z = z; } }
Now lets do some experiments.
ArrayList <ParentClass> arrayList = new ArrayList<ParentClass>(); ParentClass objp = new ParentClass(); ClassA obja = new ClassA(); ClassB objb = new ClassB(); arrayList.add(objp); arrayList.add(obja); arrayList.add(objb);
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.
Now lets try something interesting. Lets try to store object of class ClassC (which is not subclass of ParentClass) in the arraylist.
ArrayList <ParentClass> arrayList = new ArrayList<ParentClass>(); ClassC objc = new ClassC(); arrayList.add(objc);
Exception:
The method add(ParentClass) in the type ArrayList<ParentClass> 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.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Bounding ArrayList