What is the class to make Collection in Java?
Printable View
What is the class to make Collection in Java?
Vector and ArrayList are the more popular ones. I've never used ArrayList, but Vectors work like :
Thats the basics of a Vector.Code:Vector v = new Vector;
Object o = new Object();
v.addElement(o); //adds an Object to the Vector, and increases its size by 1
v.removeElement(o); //removes the Object from the Vector and decreases its size by 1
v.elementAt(index); //returns the Object at the given index
v.elements(); //returns an Enumeration of all the Objects that the Vector contains
v.contains(o); //returns true if the Object exists in the Vector
:)
Vector, ArrayList, LinkedList are off the the List interface so depending on your requirments(lists allow duplicate objects, and maintain order) you can opt to use one of these concrete implementations. If you do not wish duplicates to be stored then i would go with using a set. TreeSet is a concrete implementation
which implements the SortedSet interface so this would essentially give you order plus not allow duplicates to be stored.
To loop through a Vector that contains Strings you could do somthing like the following.
The iterator interface contains the following.Code:for(Iterator i = v.iterator();i.hasNext;){
String s = (String) i.next();
System.out.println(s);
}
public abstract boolean hasNext();
public abstract Object next();
public abstract void remove();
So what you are essentially doing is invoking a method in the Vector class that returns a refrence or a handle the iterator interface so those methods can be invoked.
wow... thank you!! Dilenger4 and crptcblade. I will try them all. Thank you for all the information on the methods too! :)
:o One more thing. The vector and hashtable classes are declared synchronized so if you are looking for better performance an ArrayList would be the way to go since it is not declared synchronized.
If you want you can actually synchronize and unsynchronized class through a decorator object.
Code:Collections syncSet = Collections.synchronizeSet(someset);
// each thread must iterate when synchronized on the decorator
synchronize(syncSet){
for(Iterator i = syncSet.iterator(); i.hasNext();){
processData(i.next());
}
}