java实验要求 (1)ArrayList 要求:包括add、get、size、indexOf、remove方法的实现。 (2)LinkedList 要求:包括put、get、remove、size方法的实现 。具体实验步骤和方法:1.ArrayList(1)add(2)get(3)size(4)indexOf(5)remove 2.LinkedList (1)add(2)get(3)size(4)indexOf (5)remove。实验步骤和方法部分需描述该功能的实现逻辑,并附上代码。
时间: 2023-12-23 11:02:43 浏览: 26
好的,下面是对题目的解答和代码实现:
1. ArrayList的实现逻辑和代码实现:
```java
import java.util.Arrays;
public class MyArrayList<E> {
private Object[] data;
private int size;
private static final int DEFAULT_CAPACITY = 10;
public MyArrayList() {
data = new Object[DEFAULT_CAPACITY];
}
public void add(E element) {
if (size == data.length) {
data = Arrays.copyOf(data, data.length * 2);
}
data[size++] = element;
}
public E get(int index) {
checkIndex(index);
return (E) data[index];
}
public int size() {
return size;
}
public int indexOf(Object element) {
for (int i = 0; i < size; i++) {
if (element.equals(data[i])) {
return i;
}
}
return -1;
}
public void remove(int index) {
checkIndex(index);
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(data, index + 1, data, index, numMoved);
}
data[--size] = null;
}
private void checkIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
}
```
2. LinkedList的实现逻辑和代码实现:
```java
public class MyLinkedList<E> {
private Node<E> head;
private int size;
public MyLinkedList() {
head = null;
size = 0;
}
public void put(E element) {
if (head == null) {
head = new Node<>(element);
} else {
Node<E> cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = new Node<>(element);
}
size++;
}
public E get(int index) {
checkIndex(index);
Node<E> cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur.data;
}
public int size() {
return size;
}
public int indexOf(Object element) {
Node<E> cur = head;
for (int i = 0; i < size; i++) {
if (element.equals(cur.data)) {
return i;
}
cur = cur.next;
}
return -1;
}
public void remove(int index) {
checkIndex(index);
if (index == 0) {
head = head.next;
} else {
Node<E> cur = head;
for (int i = 0; i < index - 1; i++) {
cur = cur.next;
}
cur.next = cur.next.next;
}
size--;
}
private void checkIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
private static class Node<E> {
E data;
Node<E> next;
public Node(E data) {
this.data = data;
this.next = null;
}
}
}
```