Showing posts with label Array List. Show all posts
Showing posts with label Array List. Show all posts

Wednesday, 12 December 2012

How to use Singleton Class ?

Leave a Comment

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.
Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

Implementing Singletons:

Example 1:

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:
// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}

// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}
This would produce following result:
demoMethod for singleton

Example 2:

Following implementation shows a classic Singleton design pattern:
public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   protected ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}
The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.
Here ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.
Read More...

Thursday, 29 November 2012

Get Sub List of Java ArrayList Example

Leave a Comment
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class GetSubListOfJavaArrayListExample {
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.     //create an ArrayList object
  9.     ArrayList arrayList = new ArrayList();
  10.    
  11.     //Add elements to Arraylist
  12.     arrayList.add("1");
  13.     arrayList.add("2");
  14.     arrayList.add("3");
  15.     arrayList.add("4");
  16.     arrayList.add("5");
  17.    
  18.     /*
  19.        To get a sub list of Java ArrayList use
  20.        List subList(int startIndex, int endIndex) method.
  21.        This method returns an object of type List containing elements from
  22.        startIndex to endIndex - 1.
  23.     */
  24.    
  25.     List lst = arrayList.subList(1,3);
  26.        
  27.     //display elements of sub list.
  28.     System.out.println("Sub list contains : ");
  29.     for(int i=0; i< lst.size() ; i++)
  30.       System.out.println(lst.get(i));
  31.      
  32.     /*
  33.       Sub List returned by subList method is backed by original Arraylist. So any
  34.       changes made to sub list will also be REFLECTED in the original Arraylist.
  35.     */
  36.     //remove one element from sub list
  37.     Object obj = lst.remove(0);
  38.     System.out.println(obj + " is removed from sub list");
  39.    
  40.     //print original ArrayList
  41.     System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
  42.     for(int i=0; i< arrayList.size() ; i++)
  43.       System.out.println(arrayList.get(i));
  44.    
  45.   }
  46.  
  47. }
Read More...

Sort Element Of ArrayList In Java

Leave a Comment
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3.  
  4. public class SortJavaArrayListExample {
  5.  
  6.   public static void main(String[] args) {
  7.    
  8.     //create an ArrayList object
  9.     ArrayList arrayList = new ArrayList();
  10.    
  11.     //Add elements to Arraylist
  12.     arrayList.add("1");
  13.     arrayList.add("3");
  14.     arrayList.add("5");
  15.     arrayList.add("2");
  16.     arrayList.add("4");
  17.  
  18.     /*
  19.       To sort an ArrayList object, use Collection.sort method. This is a
  20.       static method. It sorts an ArrayList object's elements into ascending order.
  21.     */
  22.     Collections.sort(arrayList);
  23.    
  24.     //display elements of ArrayList
  25.     System.out.println("ArrayList elements after sorting in ascending order : ");
  26.     for(int i=0; i<arrayList.size(); i++)
  27.       System.out.println(arrayList.get(i));
  28.  
  29.   }
  30. }
Read More...

Search an element from ArrayList

Leave a Comment
import java.util.ArrayList;


public class SearchElementInArrayList
{
   public static void main(String args[])
   {
       ArrayList arrList=new ArrayList();
      
       arrList.add("1");
       arrList.add("2");
       arrList.add("3");
      
       Boolean flag=arrList.contains("1");
      
       System.out.println("Contains?= "+flag);
      
       int indexNum=arrList.indexOf("1");
      
       System.out.println("Index= "+indexNum);
      
   }
}
Read More...

Replace an element in arraylist

Leave a Comment
import java.util.ArrayList;


public class ReplaceElementInArrayList
{
   
    public static void main(String args[])
    {
        ArrayList arrList=new ArrayList();
       
        arrList.add("Harit");
        arrList.add("Lalit");
       
        for(Object list:arrList)
        {
            System.out.println(list);
        }
       
        arrList.set(0,"Nikki");
       
        for(Object list:arrList)
        {
            System.out.println(list);
        }
    }

}
Read More...

Remove an element from specified index of Java ArrayList Example

Leave a Comment
  1. import java.util.ArrayList;
  2.  
  3. public class RemoveElementFromArrayListExample {
  4.  
  5.   public static void main(String[] args) {
  6.     //create an ArrayList object
  7.     ArrayList arrayList = new ArrayList();
  8.    
  9.     //Add elements to Arraylist
  10.     arrayList.add("1");
  11.     arrayList.add("2");
  12.     arrayList.add("3");
  13.    
  14.     /*
  15.       To remove an element from the specified index of ArrayList use
  16.       Object remove(int index) method.
  17.       It returns the element that was removed from the ArrayList.
  18.     */
  19.     Object obj = arrayList.remove(1);
  20.     System.out.println(obj + " is removed from ArrayList");
  21.    
  22.     System.out.println("ArrayList contains...");
  23.     //display elements of ArrayList
  24.     for(int index=0; index < arrayList.size(); index++)
  25.       System.out.println(arrayList.get(index));
  26.    
  27.   }
  28. }
Read More...

Remove all elements from Java ArrayList Example

Leave a Comment
  1. import java.util.ArrayList;
  2.  
  3. public class RemoveAllElementsOfArrayListExample {
  4.  
  5.   public static void main(String[] args) {
  6.     //create an ArrayList object
  7.     ArrayList arrayList = new ArrayList();
  8.    
  9.     //Add elements to Arraylist
  10.     arrayList.add("1");
  11.     arrayList.add("2");
  12.     arrayList.add("3");
  13.    
  14.     System.out.println("Size of ArrayList before removing elements : "
  15.                                                        + arrayList.size());
  16.     /*
  17.       To remove all elements from the ArrayList use
  18.       void clear() method.
  19.     */
  20.     arrayList.clear();
  21.     System.out.println("Size of ArrayList after removing elements : "
  22.                                                        + arrayList.size());
  23.    
  24.   }
  25. }
Read More...

Iterate a ArrayList Using Iterator

Leave a Comment
  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3.  
  4. public class IterateThroughArrayListUsingIteratorExample {
  5.  
  6.   public static void main(String[] args) {
  7.    
  8.     //create an ArrayList object
  9.     ArrayList arrayList = new ArrayList();
  10.    
  11.     //Add elements to Arraylist
  12.     arrayList.add("1");
  13.     arrayList.add("2");
  14.     arrayList.add("3");
  15.     arrayList.add("4");
  16.     arrayList.add("5");
  17.    
  18.     //get an Iterator object for ArrayList using iterator() method.
  19.     Iterator itr = arrayList.iterator();
  20.    
  21.    
  22.     System.out.println("Iterating through ArrayList elements...");
  23.     while(itr.hasNext())
        {
  24.       System.out.println(itr.next());
  25.     }
  26.   }
  27. }
Read More...

Insert all elements of other Collection to Specified Index of Java ArrayList Example

Leave a Comment
  1. import java.util.ArrayList;
  2. import java.util.Vector;
  3.  
  4. public class InsertAllElementsOfOtherCollectionToArrayListExample {
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.     //create an ArrayList object
  9.     ArrayList arrayList = new ArrayList();
  10.    
  11.     //Add elements to Arraylist
  12.     arrayList.add("1");
  13.     arrayList.add("2");
  14.     arrayList.add("3");
  15.    
  16.     //create a new Vector object
  17.     Vector v = new Vector();
  18.     v.add("4");
  19.     v.add("5");
  20.    
  21.    
  22.     //insert all elements of Vector to ArrayList at index 1
  23.     arrayList.addAll(1,v);
  24.    
  25.     //display elements of ArrayList
  26.     System.out.println("After inserting all elements of Vector at index 1,
  27.                                                    ArrayList contains..");
  28.     for(int i=0; i<arrayList.size(); i++)
  29.       System.out.println(arrayList.get(i));
  30.  
  31.   }
  32. }
Read More...

Wednesday, 28 November 2012

Copy all elements of Java ArrayList to an Object Array Example

Leave a Comment
mport java.util.ArrayList;

public class CopyElementsOfArrayListToArrayExample {

  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
  
    //Add elements to ArrayList
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
  
    /*
      To copy all elements of java ArrayList object into array use
      Object[] toArray() method.
    */
  
    Object[] objArray = arrayList.toArray();
  
    //display contents of Object array
    System.out.println("ArrayList elements are copied into an Array.
                                                  Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
      System.out.println(objArray[index]);
  }
}
 
Read More...

Append all elements of other Collection to Java ArrayList Example

Leave a Comment

import java.util.ArrayList;
import java.util.Vector;

public class AppendAllElementsOfOtherCollectionToArrayListExample {

  public static void main(String[] args) {

    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
   
    //create a new Vector object
    Vector v = new Vector();
    v.add("4");
    v.add("5");
   

   
    //append all elements of Vector to ArrayList
    arrayList.addAll(v);
   
    //display elements of ArrayList
    System.out.println("After appending all elements of Vector,ArrayList contains..");

    for(int i=0; i<arrayList.size(); i++)
      System.out.println(arrayList.get(i));

  }
}


Read More...

Array List

Leave a Comment

ArrayList

Java ArrayList is a resizable array which implements List interface. ArrayList provides all operation defined by List interface. Internally ArrayList uses an array to store its elements. ArrayList provides additional methods to manipulate the array that actually stores the elements.

ArrayList is equivalent to Vector, but ArrayList is not synchronized.

Java ArrayList Capacity

Capacity of an ArrayList is the size of the array used to store the list elements. It grows automatically as we add elements to it. Every time this happens, the internal array has to be reallocated. This increases the load.

We can set the initial capacity of the ArrayList using following method.

ArrayList arrayList = new ArrayList();
arrayList.ensureCapacity(100);

Java ArrayList Iterators
Java ArrayList provides two types of Iterators.
1) Iterator
2) ListIterator

Iterator iterator = arrayList.iterator();

Returns object of Iterator.

ListIterator listIterator = arrayList.listIterator();

Returns object of ListIterator.

ListIterator listIterator = arrayList.listIterator(int startIndex);

Returns object of ListIterator. The first next() method call on this ListIterator object will return the element at the specified index passed to get the ListIterator object.

Iterators returned by these methods are fail-fast. That means if the list is modified after getting the Iterator by using some other means rather than Iterators own add or remove method, Iterator will throw ConcurrentModificationException.

ArrayList Constructors

1) ArrayList()
Creates an empty ArrayList.

For example,
ArrayList arrayList = new ArrayList();

2) ArrayList(int capacity)
Creates an ArrayList with specified initial capacity.

For example,
ArrayList arrayList = new ArrayList(10);

3) ArrayList(Collection c)
Creates an ArrayList containing elements of the collection specified.

For example,
ArrayList arrayList = new ArrayList(myCollection);

Where myCollection is an object of the type Collection. This creates an ArrayList of elements contained in the myCollection, in the order returned by the myCollection’s Iterator.

Read More...