java使用泛型实现一个MyArrayList类
时间: 2024-01-20 19:02:22 浏览: 92
以下是使用泛型实现的MyArrayList类的示例代码:
```java
public class MyArrayList<E> {
private static final int DEFAULT_CAPACITY = 10;
private int size;
private E[] elements;
public MyArrayList() {
elements = (E[]) new Object[DEFAULT_CAPACITY];
}
public MyArrayList(int capacity) {
elements = (E[]) new Object[capacity];
}
public void add(E e) {
if (size == elements.length) {
resize();
}
elements[size++] = e;
}
public E get(int index) {
checkIndex(index);
return elements[index];
}
public void set(int index, E e) {
checkIndex(index);
elements[index] = e;
}
public E remove(int index) {
checkIndex(index);
E element = elements[index];
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
elements[--size] = null;
return element;
}
public boolean contains(E e) {
for (int i = 0; i < size; i++) {
if (elements[i].equals(e)) {
return true;
}
}
return false;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
private void resize() {
E[] newElements = (E[]) new Object[elements.length * 2];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
private void checkIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
}
```
使用示例:
```java
MyArrayList<String> list = new MyArrayList<>();
list.add("hello");
list.add("world");
System.out.println(list.get(0)); // output: hello
list.set(1, "java");
System.out.println(list.get(1)); // output: java
System.out.println(list.remove(0)); // output: hello
System.out.println(list.contains("java")); // output: true
System.out.println(list.size()); // output: 1
System.out.println(list.isEmpty()); // output: false
```
阅读全文