顺序表的功能实现代码总结
import java.util.Arrays;
public class ArrayList {
public int[] array;
public int usedSize;
public ArrayList() {
System.out.println("hahaha");
}
public ArrayList(int[] array) {
this.array = array;
}
public ArrayList(int[] array, int usedSize) {
this.array = array;
this.usedSize = usedSize;
}
public boolean isFull(){
if(this.usedSize == this.array.length){
return true;
}
return false;
}
public void resize(){
if(isFull()){
this.array = Arrays.copyOf(this.array,this.array.length * 2);
}
}
public void add(int pos, int newNumber){
if(this.array == null || this.array.length == 0){
System.out.println("链表为空 增加失败");
return;
}
if(pos < 0 || pos > this.usedSize){
System.out.println("位置错误 增加失败");
return;
}
if(isFull()){
resize();
}
for(int i = this.usedSize - 1; i >= pos; i--){
this.array[i+1] = this.array[i];
}
this.array[pos] = newNumber;
this.usedSize++;
systemArrayList();
}
public void systemArrayList(){
if(this.usedSize >= 0) {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.array[i] + " ");
}
System.out.println();
} else {
System.out.println("该链表为空");
return;
}
}
public boolean contains(int number){
for(int i = 0; i < this.usedSize; i++){
if(this.array[i] == number){
return true;
}
}
return false;
}
public int search(int number){
for(int i = 0; i < this.usedSize; i++){
if(this.array[i] == number){
return i;
}
}
return -1;
}
public int find(int pos){
if(pos < 0 || pos > this.usedSize){
System.out.println("位置错误 无法寻找");
System.out.println();
return -1;
}
return this.array[pos];
}
public void set(int pos, int value){
if(pos < 0 || pos > this.usedSize){
System.out.println("位置错误 无法寻找");
System.out.println();
return;
}
this.array[pos] = value;
systemArrayList();
}
public void del(int key){
if(contains(key)){
for(int i = search(key); i < this.usedSize - 1; i++){
this.array[i] = this.array[i + 1];
}
this.usedSize--;
if(this.usedSize == 0){
System.out.println("null");
}
systemArrayList();
} else {
System.out.println("没有找到该值");
return;
}
}
public int getUsedSize(){
if(this.array == null || this.array.length == 0){
System.out.println("链表为空 增加失败");
return -1;
}
return this.usedSize;
}
public void clean(){
this.usedSize = 0;
systemArrayList();
}
public static void main(String[] args){
int[] array = {5,5,3,4,5,6};
ArrayList arrayList = new ArrayList(array,6);
arrayList.add(5,10);
arrayList.systemArrayList();
System.out.println(arrayList.contains(5));
System.out.println(arrayList.search(5));
System.out.println(arrayList.find(3));
arrayList.set(3,5);
arrayList.del(4);
System.out.println(arrayList.getUsedSize());
for(int i = arrayList.usedSize - 1; i >= 0; i--){
arrayList.del(5);
if(arrayList.contains(5) == false){
System.out.println("关键字为5的数值都被删除完了");
break;
}
}
}
}