• 增加
      • add(data)
      • add(index,data)
      • remove(data)
      • get(index)

        1. /**
        2. * @author chenshun00@gmail.com
        3. * @since 2021/7/21 9:15 下午
        4. */
        5. public class TestArrayList<T> {
        6. private int location = 0;
        7. private Object[] elements;
        8. private int initialCapacity;
        9. public TestArrayList(int initialCapacity) {
        10. this.initialCapacity = initialCapacity;
        11. this.elements = new Object[this.initialCapacity];
        12. }
        13. public int size() {
        14. return location;
        15. }
        16. public void add(T data) {
        17. checkCapacity();
        18. elements[location] = data;
        19. location = location + 1;
        20. }
        21. public void add(int index, T data) {
        22. checkCapacity();
        23. System.arraycopy(elements, index, elements, index + 1, location - index);
        24. elements[index] = data;
        25. location = location + 1;
        26. }
        27. public boolean contains(T data) {
        28. for (Object element : elements) {
        29. if (data.equals(element)) {
        30. return true;
        31. }
        32. }
        33. return false;
        34. }
        35. public boolean remove(T data) {
        36. final int length = location;
        37. int tempIndex = -1;
        38. for (int i = 0; i < length; i++) {
        39. final Object element = elements[i];
        40. if (element.equals(data)) {
        41. tempIndex = i;
        42. break;
        43. }
        44. }
        45. if (tempIndex < 0) {
        46. return false;
        47. }
        48. System.arraycopy(elements, tempIndex + 1, elements, tempIndex, length - tempIndex);
        49. return true;
        50. }
        51. @SuppressWarnings("unchecked")
        52. public T get(int index) {
        53. return (T) elements[index];
        54. }
        55. private void checkCapacity() {
        56. boolean shouldResize = location / (initialCapacity * 1f) >= 0.75f;
        57. if (shouldResize) {
        58. initialCapacity = initialCapacity << 1;
        59. }
        60. Object[] temp = new Object[this.initialCapacity];
        61. System.arraycopy(elements, 0, temp, 0, location);
        62. elements = temp;
        63. }
        64. }