Collections


Collections


Arrays

Arrays are good to hold objects but they fall short under dynamic conditions like to add,remove ,sort , traverse .There are a number of classes and interfaces in the package java.util that are quite handy when multiple instances of some objects have to be co-located in memory .Together, the collection classes and interfaces located in java.util and java.util .concurrent are often called the Java Collection Framework.


Classes ArrayList and Vector

Arrays offer the fastest access to the collection of data, but you have to know in advance the number of elements to be stored there. Luckily Java has classes that don’t have this restriction, and you can add more elements to a collection during the run time if needed. Classes Vector and ArrayList belong to this group.
Internally both collections use the array for storage, but when you keep adding elements to these collections they internally increase the size of the array (ArrayList increases the size by smaller increments), and as elements are deleted these collections shrink.
n both Vector and ArrayList you can store only objects - only primitives are allowed. Having said this, keep in mind that Java supports autoboxing , and if you’ll try to add a primitive to a collection, it’ll be automatically converted into he corresponding wrapper object.

You have to pay a price for this convenience: ArrayList is a little slower than the array as it needs to do internal array copying to change the collection’s size, and Vector is even slower because it supports thread synchronization. But after the introduction of more efficient concurrent collections, Vector became less popular and you can achieve its synchronized functionality by using the method Collections.synchronizedList() on an ArrayList object.

No comments:

Post a Comment