Advertisement
malixds_

27

Jan 16th, 2023
891
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. package de.vogella.datastructures.list;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class MyList<E> {
  6.     private int size = 0;
  7.     private static final int DEFAULT_CAPACITY = 10;
  8.     private Object elements[];
  9.  
  10.     public MyList() {
  11.         elements = new Object[DEFAULT_CAPACITY];
  12.     }
  13.  
  14.     public void add(E e) {
  15.         if (size == elements.length) {
  16.             ensureCapa();
  17.         }
  18.         elements[size++] = e;
  19.     }
  20.  
  21.  
  22.     private void ensureCapa() {
  23.         int newSize = elements.length * 2;
  24.         elements = Arrays.copyOf(elements, newSize);
  25.     }
  26.  
  27.     @SuppressWarnings("unchecked")
  28.     public E get(int i) {
  29.         if (i>= size || i <0) {
  30.             throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i );
  31.         }
  32.         return (E) elements[i];
  33.     }
  34. }
  35.  
  36.  
  37. package de.vogella.datastructures.list;
  38. import java.util.ArrayList;
  39. import java.util.List;
  40.  
  41. import org.junit.Test;
  42.  
  43. import static org.junit.Assert.assertTrue;
  44.  
  45. public class MyListTest {
  46.  
  47.  
  48.     @Test(expected=IndexOutOfBoundsException.class)
  49.     public void testMyList() {
  50.         MyList<Integer> list = new MyList<Integer>();
  51.         list.add(1);
  52.         list.add(2);
  53.         list.add(3);
  54.         list.add(3);
  55.         list.add(4);
  56.         assertTrue(4 == list.get(4));
  57.         assertTrue(2 == list.get(1));
  58.         assertTrue(3 == list.get(2));
  59.  
  60.         list.get(6);
  61.     }
  62.  
  63.  
  64.     @Test(expected=IndexOutOfBoundsException.class)
  65.     public void testNegative() {
  66.         MyList<Integer> list = new MyList<Integer>();
  67.         list.add(1);
  68.         list.add(2);
  69.         list.add(3);
  70.         list.add(3);
  71.         list.add(4);
  72.         list.get(-1);
  73.     }
  74.  
  75.     @Test(expected=IndexOutOfBoundsException.class)
  76.     public void testList() {
  77.         List<Integer> list = new ArrayList<Integer>();
  78.         list.add(1);
  79.         list.add(2);
  80.         list.add(3);
  81.         list.add(3);
  82.         list.add(4);
  83.         assertTrue(4 == list.get(4));
  84.         assertTrue(2 == list.get(1));
  85.         assertTrue(3 == list.get(2));
  86.  
  87.         list.get(6);
  88.     }
  89.  
  90.  
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement