数组的增删改查
public interface IList {
void add(int data);
void add(int pos,int data);
boolean contains(int toFind);
int indexOf(int toFind);
int get(int pos);
void set(int pos,int value);
void remove(int toRemove);
int size();
void clear();
void display();
boolean isFull();
}
public class PosNotLegalException extends RuntimeException {
public PosNotLegalException(String msg) {
super(msg);
}
}
public class MyArrayList implements IList {
public int[] elem;
public int usedSize;
public MyArrayList(){
elem = new int[10];
}
@Override
public void add(int data) {
if(isFull()){
elem = Arrays.copyOf(elem,elem.length*2);
}
this.elem[usedSize] = data;
this.usedSize++;
}
private void checkPosOfAdd(int pos){
if(pos < 0 || pos > this.usedSize){
throw new PosNotLegalException("pos位置不合法!");
}
}
@Override
public void add(int pos, int data) {
try{
checkPosOfAdd(pos);
}catch (PosNotLegalException e){
e.printStackTrace();
}
if(isFull()){
elem = Arrays.copyOf(elem,elem.length*2);
}
for(int i = this.usedSize-1;i>=pos;i--){
elem[i+1] = elem[i];
}
elem[pos] = data;
usedSize++;
}
@Override
public boolean contains(int toFind) {
for(int i = 0;i < this.usedSize;i++){
if(this.elem[i] == toFind){
return true;
}
}
return false;
}
@Override
public int indexOf(int toFind) {
for(int i = 0;i < this.usedSize;i++){
if(this.elem[i] == toFind){
return i;
}
}
return 0;
}
private void checkPosOfGetAndSet(int pos)throws PosNotLegalException{
if(pos < 0 || pos >= this.usedSize){
throw new PosNotLegalException("pos位置不合法!");
}
}
@Override
public int get(int pos) {
try{
checkPosOfGetAndSet(pos);
}catch (PosNotLegalException e){
e.printStackTrace();
}
return elem[pos];
}
@Override
public void set(int pos, int value) {
try{
checkPosOfGetAndSet(pos);
}catch (PosNotLegalException e){
e.printStackTrace();
}
elem[pos] = value;
}
@Override
public void remove(int toRemove) {
int pos = indexOf(toRemove);
if (pos == -1){
System.out.println("没有要删除的数字!");
return;
}
for(int i = pos;i < this.usedSize-1;i++){
elem[i] = elem[i+1];
}
usedSize--;
}
@Override
public int size() {
return usedSize;
}
@Override
public void clear() {
usedSize = 0;
}
@Override
public void display() {
for(int i = 0;i < this.usedSize;i++){
System.out.print(elem[i]+" ");
}
System.out.println();
}
@Override
public boolean isFull() {
return this.usedSize == this.elem.length;
}
}