2017-04-06

Arraylist implementation

Similar question:

  •  dynamic array implementation
  •  custom arraylist implementation
  •  own arraylist implementation


  1. class MyArray<E> {
  2. static int length = 0;
  3. static int capacity = 10;
  4. static Object arr[];
  5. MyArray(){
  6.  arr = new Object[capacity];
  7. }
  8. public void add(E value) {
  9. if (capacity == length) {
  10. increaseCapacity();
  11. }
  12. arr[length] = value;
  13. length++;
  14. }

  15. public static void increaseCapacity() {
  16. capacity=capacity*2;
  17. arr=Arrays.copyOf(arr, capacity);
  18. }

  19. public static int size() {
  20. return length;
  21. }
  22. public E get(int index) {
  23. if(index>length){
  24. throw new ArrayIndexOutOfBoundsException();
  25. }
  26. else return (E) arr[index];
  27. }
  28. public boolean contain(E value) {
  29. for(int i=0;i<length;i++){
  30. if(arr[i]==value)
  31. return true;
  32. }
  33. return false;
  34. }
  35. }


Test





  1. public class Array1 {
  2. public static void main(String[] args) {
  3. MyArray m2=new MyArray();
  4. m2.add(1);
  5. m2.add("2");
  6. for (int i = 0; i < m2.length; i++) {
  7. System.out.println(m2.get(i));
  8. }
  9. }
  10. }


No comments:

Post a Comment