【Java】シーケンスチェーンの挿入、削除、検索、拡張の問題
23060 ワード
## List.java
public interface List {
//
boolean add(int element);
// index
boolean add(int index, int element);
int get(int index);
int set(int index, int val);
//
int remove(int index);
int size();
boolean isEmpty();
}
## Main.java
public class Main {
private static void test(List list) {
list.add(1);
list.add(2);
list.add(3);
list.add(4);
System.out.println(list.get(2));
System.out.println(list);
list.set(2, 100);
System.out.println(list);
System.out.println(list.size());
System.out.println(list.isEmpty());
list.remove(0);
list.remove(2);
list.remove(0);
list.remove(0);
System.out.println(list);
System.out.println(list.size());
System.out.println(list.isEmpty());
}
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
test(arrayList);
}
}
## ArrayList.java
import java.util.Arrays;
public class ArrayList implements List{
int[] array=null;
int size=0;
public void ensureCapicity(){//
if(array!=null&&size<array.length){
return;
}
int capacity=0;
if(array==null){
capacity=10;
}
else{
capacity=capacity+capacity/2;
}
if(array!=null){
array= Arrays.copyOf(array,capacity);
}
else{
array=new int[capacity];
}
}
@Override
public boolean add(int element) {
return add(size,element);
}
@Override
public boolean add(int index, int element) {
if(index<0||index>size){
System.out.println(" ");
return false;
}
ensureCapicity();
System.arraycopy(array,index,array,index+1,size-index);
array[index]=element;
size++;
return true;
}
@Override
public int get(int index) {
if (index < 0 || index >= size) {
System.out.println(" ");
return 0;
}
return array[index];
}
@Override
public int set(int index, int val) {
if (index < 0 || index >= size) {
System.out.println(" ");
return -1;
}
int oldval=array[index];
array[index]=val;
return oldval;
}
@Override
public int remove(int index) {
if (index < 0 || index >= size) {
System.out.println(" ");
return -1;
}
int oldval = array[index];
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
return oldval;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size==0;
}
public String toString(){
return Arrays.toString(Arrays.copyOf(array,size));
}
}