Advertisement
Guest User

Object Array

a guest
Apr 26th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. public class Test {
  2. public static void main(String[] args) {
  3.  
  4. // type safe to hold a list of Strings
  5. MyGenericArrayList<String> strLst = new MyGenericArrayList<String>(Integer.parseInt(args[1]));
  6.  
  7. for (int i = 0; i < strLst.size(); i++) {
  8. strLst.add("Cluck");
  9. }
  10.  
  11. for (int j = 0; j < strLst.size(); ++j) {
  12. String str = strLst.get(j); // compiler inserts the downcasting
  13. // operator (String)
  14. System.out.println(str);
  15. }
  16.  
  17. }
  18. }
  19.  
  20.  
  21.  
  22. // A dynamically allocated array with generics
  23. class MyGenericArrayList<E> {
  24. private int size; // number of elements
  25. private int index = 0;
  26. private Object[] elements;
  27.  
  28. public MyGenericArrayList(int size) { // constructor
  29. elements = new Object[size]; // allocate initial capacity of 10
  30. this.size = size;
  31. }
  32.  
  33. public void add(E e) {
  34. elements[index] = e;
  35. index++;
  36. }
  37.  
  38. public E get(int index) {
  39. if (index >= size)
  40. throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
  41. return (E)elements[index];
  42. }
  43.  
  44. public int size() { return size; }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement