View RSS Feed

My Java Tips

Bounding ArrayList

Rate this Entry
by , 11-13-2011 at 12:45 PM (1169 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.

Java Code:
Vector  vector  = new  Vector();
vector.add(1);
Exception:

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

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;
	}
}
To make the example more interesting, lets take another class ClassC which does not inherit from ParentClass.

ClassC.java

Java Code:
public class ClassC  {

	private String z;

	public String getZ() {
		return z;
	}

	public void setZ(String z) {
		this.z = z;
	}
}
Now lets do some experiments.

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);
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.

Java Code:
ArrayList  arrayList = new  ArrayList();
ClassC objc = new ClassC();
arrayList.add(objc);
Exception:


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.

Submit "Bounding ArrayList" to Facebook Submit "Bounding ArrayList" to Digg Submit "Bounding ArrayList" to del.icio.us Submit "Bounding ArrayList" to StumbleUpon Submit "Bounding ArrayList" to Google

Comments