Advertisement
Guest User

Generic arrays

a guest
Oct 15th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. public class Array<E> {
  2.  
  3.     public E[] elements;
  4.    
  5.     private int size;
  6.     private int capacity;
  7.  
  8.     @SuppressWarnings("unchecked")
  9.     public Array() {
  10.         size = 0;
  11.         elements = (E[]) new Object[(capacity = 2)];
  12.     }
  13.  
  14.     public void append(E element) {
  15.         if (size == capacity) {
  16.             @SuppressWarnings("unchecked")
  17.             E[] temp = (E[]) new Object[(capacity *= 2)];
  18.            
  19.             for (int i = 0; i < size; ++i)
  20.                 temp[i] = elements[i];
  21.            
  22.             elements = temp;
  23.         }
  24.        
  25.         elements[size++] = element;
  26.     }
  27.  
  28.     public E get(int idx) {
  29.         if (idx >= 0 && idx < size)
  30.             return elements[idx];
  31.         else
  32.             throw new IndexOutOfBoundsException();
  33.     }
  34.  
  35.     public static void doSomething(Array<Integer> arr) {
  36.         Integer good = arr.get(0);
  37.  
  38.         /*
  39.             Integer bad1 = arr.get(1);
  40.             Integer bad2 = arr.get(2);
  41.             Integer bad3 = arr.get(3);
  42.            
  43.             Replace `bad1', `bad2', and `bad3' with
  44.             these and they will work without any problems.
  45.         */
  46.  
  47.         // `bad1', `bad2', and `bad3' all produce a
  48.         // runtime exception.
  49.         Integer bad1 = arr.elements[1];
  50.         Integer bad2 = ((Integer[]) arr.elements)[2];
  51.         Integer bad3 = (Integer) arr.elements[3];
  52.        
  53.         System.out.println(good + bad1 + bad2 + bad3);
  54.     }
  55.    
  56.     public static void main(String[] args) {
  57.         Array<Integer> arr = new Array<>();
  58.         arr.append(1);
  59.         arr.append(2);
  60.         arr.append(3);
  61.         arr.append(4);
  62.         Array.doSomething(arr);
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement