Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Array<E> {
- public E[] elements;
- private int size;
- private int capacity;
- @SuppressWarnings("unchecked")
- public Array() {
- size = 0;
- elements = (E[]) new Object[(capacity = 2)];
- }
- public void append(E element) {
- if (size == capacity) {
- @SuppressWarnings("unchecked")
- E[] temp = (E[]) new Object[(capacity *= 2)];
- for (int i = 0; i < size; ++i)
- temp[i] = elements[i];
- elements = temp;
- }
- elements[size++] = element;
- }
- public E get(int idx) {
- if (idx >= 0 && idx < size)
- return elements[idx];
- else
- throw new IndexOutOfBoundsException();
- }
- public static void doSomething(Array<Integer> arr) {
- Integer good = arr.get(0);
- /*
- Integer bad1 = arr.get(1);
- Integer bad2 = arr.get(2);
- Integer bad3 = arr.get(3);
- Replace `bad1', `bad2', and `bad3' with
- these and they will work without any problems.
- */
- // `bad1', `bad2', and `bad3' all produce a
- // runtime exception.
- Integer bad1 = arr.elements[1];
- Integer bad2 = ((Integer[]) arr.elements)[2];
- Integer bad3 = (Integer) arr.elements[3];
- System.out.println(good + bad1 + bad2 + bad3);
- }
- public static void main(String[] args) {
- Array<Integer> arr = new Array<>();
- arr.append(1);
- arr.append(2);
- arr.append(3);
- arr.append(4);
- Array.doSomething(arr);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement