基于链表和数组 实现List的add和get功能
package com.arrayT;
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args) {
List li = new LinkedList();
for (int i = 0; i < 20; i++) {
li.add(" value " + i);
}
for (int i = 0; i < 20; i++) {
System.out.println(li.get(i));
}
List list = new ArrayList();
for (int j = 0; j < 20; j++) {
list.add("array" + j);
}
System.out.println(11111111);
for (int j = 0; j < 20; j++) {
System.out.println(list.get(j));
}
}
}
class ArrayList implements List {
String[] arr = new String[2];
int index = 0;
@Override
public void add(String e) {
if (index < arr.length) {
arr[index] = e;
index++;
return;
}
//arr = Arrays.copyOf(arr,arr.length * 2 );
String[] temp = new String[arr.length * 2];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
temp[index] = e;
index++;
arr = temp;
}
@Override
public String get(int index) {
if (index < 0) {
return null;
}
if (index > this.index) {
return null;
}
for (int i = 0; i < this.index; i++) {
if (i == index) {
return arr[i];
}
}
return null;
}
public void copyOf(String[] arr, String[] arr1) {
}
}
class LinkedList implements List {
class Node {
String value = null;
Node next;
public Node(String v) {
this.value = v;
}
}
int index = 0;
Node start = null;
Node last = null;
@Override
public void add(String e) {
Node node = new Node(e);
if (index == 0) {
this.start = node;
last = node;
index++;
return;
}
index++;
last.next = node;
last = node;
}
@Override
public String get(int index) {
if (index < 0) {
return null;
}
if (index >= this.index) {
return null;
}
Node temp = start;
for (int i = 0; i < this.index; i++) {
if (i == index) {
return temp.value;
}
temp = temp.next;
}
return null;
}
}
interface List {
public void add(String e);
public String get(int index);
}