简单顺序表的实现
public class MyArrayList {
public int [ ] elem;
public int usedSize;
public MyArrayList ( ) {
this . elem = new int [ 10 ] ;
}
public void add ( int pos, int data) {
if ( isFull ( ) ) {
System. out. println ( "顺序表满了,需扩容!" ) ;
this . elem = Arrays. copyOf ( this . elem, 2 * this . elem. length) ;
}
if ( pos < 0 || pos > this . usedSize) {
System. out. println ( "pos位置不合法" ) ;
return ;
}
if ( pos == this . usedSize) {
this . elem[ pos] = data;
this . usedSize++ ;
return ;
}
for ( int i= this . usedSize- 1 ; i>= pos; i-- ) {
this . elem[ i+ 1 ] = this . elem[ i] ;
}
this . elem[ pos] = data;
this . usedSize++ ;
}
public boolean isFull ( ) {
if ( this . usedSize == this . elem. length) {
return true ;
}
return false ;
}
public void display ( ) {
for ( int i = 0 ; i < this . usedSize; i++ ) {
System. out. print ( this . elem[ i] + " " ) ;
}
System. out. println ( ) ;
}
public boolean contains ( int toFind) {
for ( int i = 0 ; i < this . usedSize; i++ ) {
if ( this . elem[ i] == toFind) {
return true ;
}
}
return false ;
}
public boolean isEmpty ( ) {
return this . usedSize == 0 ;
}
public int search ( int toFind) {
for ( int i = 0 ; i < this . usedSize; i++ ) {
if ( this . elem[ i] == toFind) {
return i;
}
}
return - 1 ;
}
public int getPos ( int pos) {
if ( this . isEmpty ( ) ) {
return - 1 ;
}
if ( pos < 0 || pos > this . usedSize) {
return - 1 ;
}
return this . elem[ pos] ;
}
public void setPos ( int pos, int value) {
if ( this . isEmpty ( ) ) {
return ;
}
if ( pos < 0 || pos > this . usedSize) {
return ;
}
this . elem[ pos] = value;
}
public void remove ( int toRemove) {
int key= search ( toRemove) ;
if ( toRemove== - 1 ) {
System. out. println ( toRemove+ "不存在" ) ;
return ;
}
for ( int i= key; i< this . usedSize- 1 ; i++ ) {
this . elem[ i] = this . elem[ i+ 1 ] ;
}
this . usedSize-- ;
}
public int size ( ) {
return this . usedSize;
}
public void clear ( ) {
this . usedSize= 0 ;
}
}