fork download
  1. import java.util.AbstractList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.RandomAccess;
  5.  
  6. class Main {
  7. public static void main(String[] args) {
  8. ImmutableList<Integer> list = ImmutableList.create(1, 42);
  9. System.out.println(Arrays.asList(1, 42).equals(list));
  10. }
  11.  
  12. public static final class ImmutableList<E> extends AbstractList<E>
  13. implements List<E>, RandomAccess {
  14.  
  15. private final transient E[] arrayOfElements;
  16.  
  17. /**
  18. *
  19. */
  20. private ImmutableList() {
  21. super();
  22. arrayOfElements = null;
  23. }
  24.  
  25. /**
  26. *
  27. * Constructor with a single element
  28. *
  29. * @param <E>
  30. * type of element
  31. * @throws NullPointerException
  32. */
  33. private ImmutableList(E element) {
  34. super();
  35. if (element == null)
  36. throw new NullPointerException();
  37.  
  38. int i = 0, length = 0;
  39. length = (this.arrayOfElements == null ? 1
  40. : this.arrayOfElements.length + 1);
  41. @SuppressWarnings("unchecked")
  42. E[] tempArray = (E[]) new Object[length];
  43.  
  44. if (this.arrayOfElements == null) {
  45. tempArray[length - 1] = element;
  46. } else {
  47. for (i = 0; i < tempArray.length; i++) {
  48. tempArray[0] = this.arrayOfElements[i];
  49. }
  50. tempArray[i] = element;
  51. }
  52.  
  53. this.arrayOfElements = tempArray;
  54. }
  55.  
  56. /**
  57. *
  58. * Constructor with an array elements
  59. *
  60. * @param element
  61. * @throws NullPointerException
  62. */
  63. @SafeVarargs
  64. private ImmutableList(E... elements) {
  65. super();
  66. if (elements == null)
  67. throw new NullPointerException();
  68. this.arrayOfElements = Arrays.copyOf(elements, elements.length);
  69. }
  70.  
  71. public static <E> ImmutableList<E> create(E element) {
  72. return new ImmutableList<E>(element);
  73. }
  74.  
  75. public static <E> ImmutableList<E> create(E[] arrayofEl) {
  76. return new ImmutableList<E>(arrayofEl);
  77. }
  78.  
  79. @SafeVarargs
  80. public static <E> ImmutableList<E> create(E elt, E... arrayOfEl) {
  81. @SuppressWarnings("unchecked")
  82. E[] tempArray = (E[]) new Object[arrayOfEl.length + 1];
  83. tempArray[0] = elt;
  84. for (int i = 1; i < tempArray.length; i++) {
  85. tempArray[i] = arrayOfEl[i - 1];
  86. }
  87. return new ImmutableList<E>(tempArray);
  88. }
  89.  
  90. public static <E> ImmutableList<E> create() {
  91. return new ImmutableList<E>();
  92. }
  93.  
  94. @Override
  95. public E get(int index) {
  96. return arrayOfElements[index];
  97. }
  98.  
  99. @Override
  100. public int size() {
  101. return arrayOfElements.length;
  102. }
  103. }
  104. }
Success #stdin #stdout 0.06s 215488KB
stdin
Standard input is empty
stdout
true