Force Collections to Accept Only One Data Type in Java
Collections, such as ArrayList and Set, in Java used to be able to contain any class. So you could implement the following code without a problem.
ArrayList oldWay = new ArrayList(); oldWay.Add("xyz"); oldWay.Add(456); oldWay.Add(new CustomWhatever());
But sometimes this flexibility caused problems because you might want to limit what could be contained in that list (for example, limit it to String objects). That way when you retrieved an object from that list you wouldn’t have to check that it was the class you wanted it to be.
Well, in newer versions of Java, you can use generics to limit collections. Here’s an example:
ArrayList<String> newWay = new ArrayList<String>(); newWay.Add("xyz"); newWay.Add("qrs");
You can still do it the old way, but this way has a lot of advantages.
For more details about this, see this post that explains a similar concept.