Saturday, September 19, 2015

[Java] Enums

1. Example
// Think of it as constant value
Currency usCoin = Currency.DIME;
if (  usCoin == Currency.DIME )


public class CurrencyDenom
{
         public static final int PENNNY = 1;
         public static final int NICKLE = 5;
         public stati final int DIME  =10;
         public static final int QUARTER = 25;
}
public class Currency
{
         private int currency;// CurrencyDenom.PENNY, CurrencyDenom.NICKLE 
                                         // CurrencyDenom.DIME, CurrencyDenom.QUARTER
}


Limitations:
1) No type-safety
currency can be assigned any value
2)No meaningful printing
print "NICKLE" print "5" instead of "NICKLE"
3)No namespace
need to access by class name like CurrencyDenom.PENNY instead of PENNY

2. Implementation

public enum Currency
{
     PENNY, NICKLE, DIME, QUARTER
};

Java Enum is type like class and interface and can be used to define a set of constants.



1) Type-safety
Currency coin = Currency.PENNY;
coin =1; // compilation error

2) Reference type
can define CONSTRUCTOR, method and variables

3) Specify values of enum constants at the creation time
public enum Currency{PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
NOTE: for this to work you need a member variable and a constructor because PENNY(1) is actually calling a CONSTRUCTOR which accepts int value, see below example

public enum Currency 
{
      PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
      private int value;
      private Currency(int value) { this.value = value;}

}
Constructor of enum in java must be private (LIKE a singleton )any other access modifier will result in compilation error.
Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.

4) Enum constants are implicitly static and final and can not be changed once created.
Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be assigned.

5) Use in switch like char or int
Currency usCoin = Currency.DIME;
switch(usCoin)
{
        case PENNY:
           break;
        case NICKLE:
           break;
        case DIME:
          break;
        case QUARTER:
//NOTE:  no need to break in the last case, it won;t be overwritten
}

6) Equality operator
Currency usCoin =  Currency.DIME;
if (  usCoin == Currency.DIME )
{
     System.out.println("enum in java can be compared using ==");
}


NOTE: comparing objects using == operator is not recommended, Always use equals() method or compareTo() mehtod to compare Objects.

7) automatically generate "static" values() [static use class to call], which return array of Enum constants in the same order.
for ( Currency coin:Currency.values() )
         System.out.println("coin: " + coin);

coin:PENNY
coin:NICKLE
coin:DIME
coin:QUARTER

8)Meaningful printing, override toString()
public enum Currency {

........
@Override
public String toString()
{
       switch (this)
       {
                case PENNY:
                     break;
                case NICKLE:
                     break;
                case DIME:
                     System.out.println("Dime: "+ value);
                     break;
                case QUARTER:
       }

       return super.toString();
}

};
Currency usCoin = Currency.DIME;
System.out.printon(usCoin);

Output:
Dime:10



9) EnumMap and EnumSet
10) You can not create instance of enums by using new operator because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
11) Instance of Enum in Java is created when any of Enum constants are first called or referenced in code.
12)  Implement the interface 
It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface

public enum Currency implements Runnable
{
     PENNY (1), NICKLE(5), DIME(10), QUARTER(25);
     private int value;
     ........
     @Override
      public void run ()
      {
              System.out.println("Enum in java implement interfaces");
      }

     
}


13) Define abstract method
public enum Currency implements Runnable
{
       PENNY(1)
       {
                  @Override
                   public String color()
                   {
                           return "copper";
                   }
       },
       NICKLE(5)
       {
                   @Override
                   public String color()
                   {
                           return "bronze";
                   }
       },
       DIME(10)
       {
                   @Override 
                   public String color()
                  {
                           return "silver";
                  }
       },
       QUARTER(25)
       {
                    @Override
                     public string color()
                    {
                           return "silver";          
                    }
       }

       private int vlaue;
       public abstract String color();
       private Currency (int vlaue)
       {
                  this.vlaue = vlaue;
       }

}

In this example since every coin will have different color we made the color() method abstract and let each instance of Enum to define there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:
System.out.println("Color: " + Currency.DIME.color());


14) Enum valueOf(String) :convert a String into enum
num valueOf() is a static method which takes a string argument and can be used to convert a String into enum. 
One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.


enum Mobile {
   Samsung(400), Nokia(250),Motorola(325);
  
   int price;
   Mobile(int p) {
      price = p;
   }
   int showPrice() {
      return price;
   } 
}
Mobile ret;
     ret = Mobile.valueOf("Samsung"); 
     System.out.println("Selected : " + ret);   
Selected : Samsung
http://www.tutorialspoint.com/java/lang/enum_valueof.htm 
15) ordinal() and name(Enum):
converting Enum to String 
ordinal() method of Java Enum returns position of a Enum constant as they declared in enum.
name() of Enum returns the exact string which is used to create that particular Enum constant.
name() method can also be used for converting Enum to String in Java.

  Mobile ret = Mobile.Motorola;
     System.out.println("MobileName = " + ret.name()); 
MobileName = Motorola
http://www.tutorialspoint.com/java/lang/enum_name.htm 
3. similar ones



[Snapchat] Celebrity Problem

1. Example

N people , only one person is known to everyone.
Find out the minimum question need to ask to find the celebrity?

A <-  B <- D
 A <-C < -B
A<-  D < -E
A<- E <-B
2. Implementation
Methods1 n*n
Q1: ask anyone whom he or she know?
A1: nxn matrix, aij=1 means i know j, otherwise 0.
So all i know j means column j all 1, j is the celebrity. Otherwise, there is no celebrity.
Methods2 n-1 + 2n-2
Q1: bubble ask ABCDE
A1:
STEP1 : 1 question former knows later
1 Questions*(N-1 ) person
A vs B,(A knowB) take out A or B and leave A or B keep going down
? knows C
? knows D
? knows E
STEP2: 2 question , (LEFTOVER!= later)LEFTOVER knows later or later knows LEFTOVER
2Questions * (N-1) person
Methods3 n-1 + 2n-2 - log2n (n-1 + 2n-2 is like Methods2 when one left we need to ask thru all other uses but there are already log2n have been asked in the TREE)
n = 2^k
Q1: two person a pair and within a pair, they ask to each other
A1: (A,B) eliminate one person by asking if A knows B. Left n/2 persons. Until 1 left
BINARY TREE
N/2(level 1) + N/4(level 2)+..+1(level k)= N(1/2+1/4+...1/2^k)= N-1
N = 8 = > 7 Qs

   1 2    3y  4'   5 6   7 8
     1y     4'         6     7
         4'                  6y
                  4'
http://www.slideshare.net/SriHarsha1508/lec10-31843573

3. Similar Ones

Friday, September 18, 2015

[Backtracking] N-Queens

1. Example

row         : two queens cannot be placed in the same row
column   : two queens cannot be placed in the same column
diagonal : two queens cannot be placed in the diagonal position


[
[".Q..", // Solution 1
 "...Q",
 "Q...",
 "..Q."],

 ["..Q.", // Solution 2
 "Q...",
 "...Q",
 ".Q.."]
]

Q1: '.' or 'Q'
A1: board => n^2 for time and space
Q1: how to check?
A1: valid (i,j) = > queenatcolumn[i] != -1 => OCCUPIED
                            any i make  j   == queenatcolumn[i], i =0-n-1 => OCCUPIED
|i-rowIndex |  == |column -queenatcolumn[rowIndex] |, for all queenatcolumn[i], i = 0~ n-1
Q
   Q     |1-0| == |1-0|
    Q
Q       | 1-0| =| 0-1|
like above case
row1   1
row2   3
row3   0
row4   2
Q1: how to iterate?
A1: 

2. Implementation
//NOTE
QueenAtColumn[row] = j; if ( isValid(row, QueenAtColumn) ) helper(n, row+1, QueenAtColumn, res);

// Time:O(n), Space:O(n) call stack 
public List solveNQueens(int n)
{
    


     List res = new ArrayList();
     if (n <= 0)
          return res;
    
    
     helper(n, 0,new int[]  ,res );



     return res;



}
//private void helper( int n, int start ,int[] QueenAtColumn, List res  )
private void helper( int n, int row ,int[] QueenAtColumn, List res  )
{




     if ( row == n)
     {
          String[] item = new String[n]; 
          for (int i =0 ; i < n;i++)
          {
              StringBuilder sb = new StirngBuilder(); 
              for (int j = 0; j < n; j++ )
              {     
                  if ( QueenAtColumn[i] == j)
                       sb.append('Q');
                  else 
                       sb.appned('.');
              }
              item[i] = sb.toStirng();   
          }
          res.add(item);
          return;
     }




     for (int j =0; j < n; j++)
     {
         QueenAtColumn[row] = j;
         if (  isValid(row, QueenAtColumn) ) 
               helper(n, row+1, QueenAtColumn, res);     
     }




}
//private boolean isValid (int row, int column ,int[] QueenAtColumn)
//private boolean isValid (int row,int[] QueenAtColumn)

{
        

    // check row
    //if ( QueenAtColumn[row] !=  )
    //     return false;


    // check column
    //for (int i = 0 ; i < n ; i++)
    //{
    //     //if ( QueenAtColumn[i] == column )
    //          return false;
    //}



    // check diagonal NOTE: AND COLUMN
    for (int i = 0; i < n; i++)
    {
         //if ( Math.abs(row-i) == Math.abs(QueenAtColumn[i] - column ))
         if ( Math.abs(row-i) == Math.abs(QueenAtColumn[i]-QueenAtColumn[row])  || QueenAtColumn[row] == QueenAtColumn[i] )
              return false;
    }



    return true;


  
}
3. Similar ones
N-Queens II
Sudoku solver

Thursday, September 17, 2015

[Backtracking]Sudoku Solver

1. Example

row : there exists only 1-9, no duplicate
column: there exists only 1-9, no duplicate
block : there exists only 1-9, no duplicate



2. Implementation

 // NOTE :empty already checked
 if ( board[m][n]== board[i][j] && (m!=i || n != j) ) return false;


// NOTE :empty already checked and cell present itself well
 if ( board[k][j] == board[i][j] && K!= i ) return false;
// NOTE: no way to below 0 and
 if ( j >= 9) return helper(board, i+1, 0);

// NOTE: make sure empty then try diff values
 if ( board[i][j] == '.') { 
     for (int v =1 ; v <= 9 ; v++) {
         board[i][j] = ((char) v+'0');

public void solveSudoku( char[][] board )
{
    

     //validate the input
     if ( board == null || board.length == 0 || board[0].length == 0) 
         return;


  
     helper(board, 0,0);
     


}
//private void helper(char[][] board, int i, int j)
private boolean helper(char[][] board, int i, int j)
{




     //validate the input
     //if (board == null || i< 0|| i>=board.length || j <0 data-blogger-escaped-j="">board[0].length)
     //   return;
     //if (j== board[0].length)
     //    i++;



     // NOTE: no way to below 0 and 
     if ( j >= 9)
         return helper(board, i+1, 0);
     if (i == board.length)
         return true;





     // NOTE: make sure empty then try diff values
     if ( board[i][j] == '.') 
     {
          for (int v =1 ; v <= 9 ; v++)
          {
        
              //if ( board[i][j] == '.' && isValid(board,i,j,v)  )
              // NOTE: board[][] should check first, otherwise we will lose a number to check
              //{      
                


                board[i][j] = ((char) v+'0');
                



                if ( isValid(board, i ,j)  )
                {
                   if (  helper(board, i, j+1) )
                      return true;
                }     



                //helper(board, i, j+1);
                board[i][j] = '.';




               //}
           }
     }
     else 
     {

        helper(board, i,j+1);
     }



     return false;


}
//private boolean isValid(char[][] board, int i , int j, int target)
// NOTE: board cell present its value, not the parameter target
private boolean isValid(char[][] board, int i, int j)
{



     // check row
     for (int k = 0 ; k < board[0].length; k++ )
     {
           //if (board[i][k]!='.'  && ((int)(board[i][k]-'0')) == target && k != j)
           // NOTE :empty already checked and cell present itself well
           if ( board[i][k] == board[i][j] && k!= j  )
                return false;
     }




     // check column
     for ( int k = 0 ; k < board.length; k++ )
     {
           //if (board[k][j] !='.' && ((int)(board[k][j] -'0')) == target && k!= i )
           // NOTE :empty already checked and cell present itself well
           if ( board[k][j] == board[i][j] && K!= i )
                return false;
     }




     // check block
     for (int m =( i/3 )*3; m < ( i/3 )*3 +3 ;m++ )
     {
        for (int n = (j/3)*3; n < (j/3)*3 + 3;n++ )
        {
            //if (board[m][n] != '.' && (int)(board[m][n]-'0') == target && m!= i && n != j)
            // NOTE :empty already checked and  cell present itself well
            if (  board[m][n]== board[i][j]  && (m!=i || n != j) )
                 return false;
        }
     }


     return true;


}
3. Similar Ones
Valid sudoku

[valid sudoku]

1. Example

row      : there exists only 1-9, no duplicate
column: there exists only 1-9, no duplicate
block   : there exists only 1-9, no duplicate

2. Implementation


// Time:O(3* n^2), Space:O(n)
public boolean isValidSudoku( char[][] board )
{



     // validate the input
     if ( board == null || board.length == 0 || board[0].length == 0 ) 
          return false;



     
     // check row     
     for ( int i = 0 ; i < board.length;i++ )
     {
          boolean[] digit = new boolean[9];
          for ( int j = 0 ; j < board[0].length; j++ )
          {
              // NOTE: EMPTY is allowed
              if ( board[i][j] != '.' ) 
              {   
              if (  digit[(int)(board[i][j] - '0')-1]  ) 
              {
                   return false;
              }
              //else
              //{
                   digit[(int)(board[i][j] - '0')-1] = true;
              //} 
              }
          }
     }





     // check column     
     for ( int j = 0 ; j < board[0].length;j++ )
     {
          boolean[] digit = new boolean[9];
          for ( int i = 0 ; i < board.length; i++ )
          {
              // NOTE: EMPTY is allowed
              if ( board[i][j] != '.' )
              {
              if (  digit[(int)(board[i][j] - '0')-1]  ) 
              {
                   return false;
              }
              //else
              //{
                   digit[(int)(board[i][j] - '0')-1] = true;
              //}
              } 
          }
     }




     // check block
     // 0 - 012   1 - 345  2 - 678
     // 3         4        5
     // 6         7        8
     for ( int k = 0 ; k < 9; k++ ) 
     {
          boolean[] digit = new boolean[9];
          //for (int i = (k%3)*3; i < (k%3)*3+3;i++ )
          for (int j = (k/3)*3; j < (k/3)*3+3; j++ )
          {
               //for (int j = (k/3)*3; j < (k/3)*3+3; j++ )
               for (int i = (k%3)*3; i < (k%3)*3+3;i++ )
               {
                   // NOTE: EMPTY is allowed
                   if ( board[i][j] != '.' )
                   {
                   if (  digit[(int)(board[i][j] - '0')-1]  ) 
                   {
                       return false;
                   }
                   //else
                   //{
                       digit[(int)(board[i][j] - '0')-1] = true;
                   //}
                   }                
               }
          }
     }



    
     return true;



}
3. Similar Ones
Sudoku solver

[Sweep Line Algo][Divide And Conquer][Heap]The Skyline Problem

1. Example
TRICK: 
Start look max(compare with pq.peek(), peek() not change, skip this start ), 
End look min ( remove this height, pq.peek() look for min)
15   |          __
12   |         |    |____    
10   |       _|_| |__    |      ___
       |      |  |  | |    |   |      |     _| _  
 8    |      |  |  | |    |   |      |    |  |    |
       |___|_|_| |__|_ |___|__|  |_  |_
              2 3 7  9   12   15  20  24
                                        19
[2 9 10]
[3 7 15]
[5 12 12 ]
[15 20 10]
[19 24 8]


15   |          __
12   |         |    |____    
10   |       _|            |        ___
       |      |               |       |       | _  
 8    |      |               |       |           |
       |___|__      __ |_     |___ __|_
              2 3 7  9   12   15  20  24
                                        19
[2 10]
[3 15]
[7 12]
[12 0]
[15 10]
[20 8]
[24 0]

References:
http://yuanhsh.iteye.com/blog/2217735
http://www.shuatiblog.com/blog/2014/07/01/The-Skyline-Problem/
2. Implementation
Q1: find the highest edge and keep scrolling down?
A1: highest edge 3  15
                            7 15
                            7 12
                           12 12
                             2 10
                            9  10
                         15 10
                          20 10
                         24 8
2 0
12 0
15 0
24 0
Q1: Priority Queue <-> Heap

3,7,2,4,1,5
min heap default
   3
-----
   3
7
-----
    3
7   2
-----
  2
7  3  heapify
------
    2
  7 3
4
-----
   2
 4    3
7        heapify
-------
     2
  4   3
7 1
------
     2
  1   3
7  4     heapify
------
     1
  2   3
7 4      heapify
---------
     1
  2     3
7 4  5     DONE!!

1  2  3   4   5  6
1, 2, 3,  7, 4,  5
1,,2,,4,,,3,,7,,,5
[3 7 2 4 1 5]
Left child(i) = at position 2i
Right child(i) = at position 2i+1
Parent(i) = at position floor(i/2)
  0  1  2  3 4  5 6  7  8  9 10
["",A,B,C,D,E,F,G,H, I, J,..]<= Queue
                           A
               B 2(P)          C
      D 4         E         F     G  <= Heap
 H 8(L) I    I9(R)
1. Insert
Insert new element into the heap at the next available slot ( next available slot ( hole )
2. DeleteMin
Move last element into hole at root
Construct heap from initial set of N items
  Solution 1  Perform N inserts  O(N log2 N) worst-case
  Solution 2 (use buildHeap())  Randomly populate initial heap with structure property
  Perform a percolate-down from each internal node (H[size/2] to H[1]) (H[size/2] to H[1])
 To take care of heap order property
Height of heap is
 insert: O (lg N ) for each insert
 log 2 N  (g )  In practice, expect less
 buildHea p () insert: O ( N ) for N inserts
 deleteMin: O(lg N)
  decreaseKey: O(lg decreaseKey: O(lg N)
 increaseKey: O(lg N)
 remove: O(lg remove: O(lg N)


把所有的turning points 放在一起,根据coordination从小到大sort 。
再用max-heap, 把所有的turning points扫一遍,遇到start turning point, 把 volume放入max-heap. 遇到end turning point,把对应的volume从max-heap中取出。
max-heap的max 值就是对应区间的最大volume


if ( h[1] < 0 ) { 
 pq.offer(-h[1]); } 
 else {
 pq.remove(h[1]); }
// Time:O(nlogn) , Space:O(n)
public List getSkyLine(int[][] buildings)
{



    List result = new ArrayList<>();
    // validate the input
    if ( buildings == null || buildings.length ==0 || buildings[0].length ==0 )
        return result;
   




    List height = new ArrayList<>();
    for (int[] b:buildings)
    {
        height.add( new int[]{ b[0], -b[2]   });// start , -height
        height.add( new int[]{ b[1],  b[2]   });// end , height
    }    



   
    Collections.sort(   height, new Comparator(){
        public int compare(int[] a, int[] b)
        { 
            if ( a[0] != b[0]) return a[0] - b[0];
            return a[1]-b[1];
        }
        
    }   );






    Queue pq = new PriorityQueue<>(){
        public int compare(Integer a, Integer b)
           return b-a;// descending        
    }); 
   
    


 // Input : [2,-10][3,-15][5,-12][7,15][9,10][12,12][15,-10][19,-8][20,10][24,8]
//  Result: [2 10],[3 15],[7 12],[12 0],[15 10],[20 8],[24, 0]
//[2 -10]=>    (10 0),         pre=0!=10  ,RES.ADD[2,10], pre =10
//[3,-15]=>    (15 10,0),      pre=10!=15 ,RES.ADD[3,15], pre =15
//[5 -12]=>    (15 12 10 0),   pre =15==15,RES NOT ADD  , pre =15
//[7,15]remove 15 (12 10 0),    , pre =15!=12,RES.ADD[7,12], pre =12
//[9,10]remove 10 (12 0 ),        pre =12==12,RES NOT ADD,   pre =12
//[12,12]remove12 (0),            pre =12!=0 ,RES.Add[12,0], pre = 0
//[15,-10]        (10 0)          pre =0!= 10,RES.Add[15,10],pre =10
//[19,-8]         (10 0 8)        pre =10==10,RES NOT ADD   ,pre =10
//[20,10]         (8 0)           pre =10!= 8,RES.ADD[20,8], pre = 8
//[24,8]          (0)             pre =0!=8  ,RES.ADD[24,0]
    pq.offer(0);
    int prev = 0;
    for (int[] h: height)
    {
         if ( h[1] < 0 )
         {
            pq.offer(-h[1]);
         }
         else 
         {
            pq.remove(h[1]);
         }

         int cur = pq.peek();
         if ( prev != cur )
         {
              result.add(   new int[] {h[0], cur});
              prev = cur;
         }
    }


    
     return result;

}
public int[] skyline( List bds, int min, int max)
{


     int[] output = new int[max-min];


     List[] edges = new List[max-min];
     for (int i = 0; i < edges.length;i++)
         edges[i] = new ArrayList();




     for (Building b: bds)
     {
            edges[b.from].add( new Edge(b, true) );
            edges[b.to].add(   new Edge(b, false)  );
     }



     Queue heap = new PriorityQueue(100,
new ComparatoR
     {
       public int ocmpare (Buildign b1, Building b2)
          return b2.hieght-b1.height;
     });


    
     
     for (int i = 0 ; i < edges.length; i++)
     {
         for ( Edge e, edges[i])
         {
              if ( e.isEnter)
                   heap.add(e.building);
              else
                   heap.remove(e.building);
         }


         if (!heap.isEmpty())
              output[i] = heap.peek().height;
     }
}

static class Edge {
    Building building;
    boolean is Enter;
    public Edge(Building old, boolean enter)
    {
        building = old;
        isEnter = enter;
    }
}
static class Building
{
    int from;
    int to;
    int height;
    public Building (int a, int b, int c)
    {
      from=a; to= b;height=c; 
    }
}




3. Similar Ones
[1]Given n line segments, find if any two segments intersect
http://www.geeksforgeeks.org/given-a-set-of-line-segments-find-if-any-two-segments-intersect/





[2]这样的,两个input,第一个是一个机器的total_mem,第二个是一堆job,每个job包含starting_time,duration,mem_needed,mem_needed就是说这个工作需要这么多的memeory。要求是输出bool,表示是否在任意时间内,所有重叠工作的memory总和都不能超过total_mem。也就是测试这个机器的total_mem够不够大。
每个job有一个time interval, sorted according to start time, loop each interval, for each interval, loop previous interval to see if previous jobs ended. Calculate memory and compare with total memory. Time complexity will be O(n^2). 没有前面提供的优化~
一个job变成两个事件点
Event{. visit 1point3acres.com for more.
bool is_in;
int time;
int mem_used;.
}

比如job 从 0开始 10结束,用了200mem
Event{true,0,200}, Event{false,10,200}
按照time排序,time相同,is_in = false的优先。

然后你扫过去, is_in=true的你就加mem,is_in=false的你就-mem.每个事件点,你会加或减一次,每加或减一次后,就check是不是超过总的。

Sunday, September 13, 2015

[Data Structure] Set Implementation



public class Set {
      private T arrayElement[];
      int size =0;
      public Set(){
            this.arrayElement = null;
  	}
      public Set(T[] element){
        	arrayElement = element;// array can be assigned
        	size = arrayElement.length;
  	}
  	/**
  	 *add element to set. A check is made to identify whether element is present or not.
  	 *If not the element can be inserted.
  	 * @param element
  	 */
      public void addElement(T element){
            if(!contains(element)){
                    if(size == arrayElement.length){
              	       incrementArray();
        	          }
        	          arrayElement[size++] = element;
        	  }
       }
     
  	/**
  	 * to check is element is present or not.
  	 * @param elem
  	 * @return boolean
  	 */
O(n)
      public boolean contains(T elem){
 
            if (elem == null) {
        	    for (int i = 0; i < size; i++)
                  if (arrayElement[i]==null)
              	    return true;
        	} else {
        	    for (int i = 0; i < size; i++)
                  if (elem.equals(arrayElement[i]))
              	    return true;
        	}
            return false;
  	   
  	}
     	/**
  	 * this function is used to increment the size of an array
  	 *
  	 */
      private void incrementArray(){
        	T[] temparray = arrayElement;
            int tempsize=size+5;
        	 arrayElement =(T[]) new Object[tempsize];
        	 System.arraycopy(temparray, 0, arrayElement, 0, size);
        	 
  	}
public static void arraycopy(Object src,
                             int srcPos,
                             Object dest,
                             int destPos,
                             int length)
http://www.java-samples.com/showtutorial.php?tutorialid=641 
The difference is that Arrays.copyOf does not only copy elements, it also creates a new array.System.arrayCopy copies into an existing array.
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]
http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/
  	/**
  	 * return the size of set.
  	 * @return int
  	 */
      public int size(){
            if(arrayElement != null){
                  return arrayElement.length;
        	}else
                  return 0;
  	}
     
      public void clear(){
        	arrayElement = null;
  	}
     
      public String toString(){
            if(arrayElement == null  || arrayElement.length ==0 ){
                  return“[EMPTY]”;
        	}else{
              	String toStr=”[“;
                  for(int i=0;i