This is my first blog entry on java technologies. My friend asked me why I don’t publish articles on Java. So i ama little excited. Well, Today we glance at Collection on java. A collection in data structure terms, is a group of elements.It includes Sets and Lists. It also includes Maps which don’t implement Collection. Collection is the interface implemented by classes such as Arraylists,TreeSet and HashSet implement. It defines to methods to them all. Collection classes live in java.util package. I want to give ArrayList and LinkList Class example that implements List interface
public class Data {
protected int myArray [];
public int size ;
public Data()
{
myArray = new int [50];
}
public Data (int n)
{
myArray = new int[50];
size =n;
}
protected void finalize() {
System.out.println(“cleaned” + size);
}
}
import java.util.*;
public class ArrayListExample
{
public static void main(String[] args) {
ArrayList l = new ArrayList();
int sizeOfL ;
for (int i = 0; i<5; i++)
{
l.add(new Data(i));
}
sizeOfL = l.size();
for (int i = 0; i <sizeOfL; i++) {
int size =((Data) l.get(i)).size;
System.out.println(“elements 1…” + size);
}
l.add(0, new Data(6)); // 6,0,1,2,3,4
l.add(2, new Data(17)); // 6,0,17,1,2,3,4
sizeOfL = l.size();
for (int i = 0; i <sizeOfL; i++) {
int size =((Data) l.get(i)).size;
System.out.println(“elements 2….” + size);
}
l.remove(3); //6,0,17,2,3,4
List sub = l.subList(1, 3); // 0,17
}
}
A LinkedList is similar to an ArrayList in that it is ordered by index position. If you want to have random access of the list
Arraylist offers quick access than LinkList but this comes at slower operations for adding and removing in the middle of the
list.
Vector is synchronized whereas ArrayList is not.ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.Arraylist has no default size but vector has size of ten. We can see using capacity()method.
import java.util.*;
public class Demo1 {
public static void main(String[] args) {
//creating vector
Vector v= new Vector();
v.add(“baran”);
v.add(“ipek”);
//creating enumeration interface
Enumeration E=v.elements();
System.out.println(“Element are : “);
while(E.hasMoreElements())
{
System.out.println(E.nextElement()+”\t”);
}
//Returns the current capacity of this vector.
int i=v.capacity();
System.out.println(“Capacity of the vector is: “+i);
}
}