Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test {
- public static void main(String[] args) {
- // type safe to hold a list of Strings
- MyGenericArrayList<String> strLst = new MyGenericArrayList<String>(Integer.parseInt(args[1]));
- for (int i = 0; i < strLst.size(); i++) {
- strLst.add("Cluck");
- }
- for (int j = 0; j < strLst.size(); ++j) {
- String str = strLst.get(j); // compiler inserts the downcasting
- // operator (String)
- System.out.println(str);
- }
- }
- }
- // A dynamically allocated array with generics
- class MyGenericArrayList<E> {
- private int size; // number of elements
- private int index = 0;
- private Object[] elements;
- public MyGenericArrayList(int size) { // constructor
- elements = new Object[size]; // allocate initial capacity of 10
- this.size = size;
- }
- public void add(E e) {
- elements[index] = e;
- index++;
- }
- public E get(int index) {
- if (index >= size)
- throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
- return (E)elements[index];
- }
- public int size() { return size; }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement