自定义ArrayList(简单易懂)
1.MyArrayList类
package MyArrayListDemo;
public class MyArrayList {
public int [ ] elem;
public int usedSize;
public MyArrayList ( ) {
this . elem = new int [ 10 ] ;
this . usedSize = 0 ;
}
public MyArrayList ( int capacity) {
this . elem = new int [ capacity] ;
this . usedSize = 0 ;
}
public int size ( ) {
return this . usedSize;
}
public void add ( int pos, int data) {
if ( pos < 0 || pos > this . usedSize) {
System. out. println ( "位置不合法!" ) ;
return ;
}
if ( usedSize == elem. length) {
System. out. println ( "添加失败!数组已满" ) ;
return ;
}
for ( int i = usedSize - 1 ; i >= pos; i-- ) {
elem[ i + 1 ] = elem[ i] ;
}
elem[ pos] = data;
this . usedSize++ ;
}
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 : this . elem) {
if ( i == toFind) {
return true ;
}
}
return false ;
}
public int search ( int toFind) {
for ( int i = 0 ; i < this . elem. length; i++ ) {
if ( toFind == elem[ i] ) {
return i;
}
}
return - 1 ;
}
public int getPos ( int pos) {
if ( pos < 0 || pos >= this . usedSize) {
return - 1 ;
}
return this . elem[ pos] ;
}
public int setPos ( int pos, int value) {
if ( pos < 0 || pos >= this . usedSize) {
return - 1 ;
}
elem[ pos] = value;
return elem[ pos] ;
}
public void remove ( int toRemove) {
int index = search ( toRemove) ;
if ( index != - 1 ) {
for ( int i = index; i < usedSize - 1 ; i++ ) {
elem[ i] = elem[ i + 1 ] ;
}
this . usedSize-- ;
} else {
System. out. println ( "您要删除的值不存在!" ) ;
}
}
public void removeByPos ( int pos) {
int value = getPos ( pos) ;
if ( value != - 1 ) {
remove ( value) ;
} else {
System. out. println ( "删除失败!" ) ;
}
}
public void removeAll ( int toRemove) {
for ( int i = usedSize - 1 ; i >= 0 ; i-- ) {
remove ( toRemove) ;
}
}
public void clear ( ) {
this . usedSize = 0 ;
}
}
2.测试类MyArrayListTest
package MyArrayListDemo;
public class MyArrayListTest {
public static void main ( String[ ] args) {
MyArrayList myArrayList = new MyArrayList ( ) ;
myArrayList. add ( 0 , 4 ) ;
myArrayList. add ( 0 , 4 ) ;
myArrayList. add ( 0 , 4 ) ;
myArrayList. add ( 0 , 4 ) ;
myArrayList. add ( 0 , 4 ) ;
myArrayList. add ( 0 , 4 ) ;
myArrayList. display ( ) ;
myArrayList. remove ( 4 ) ;
myArrayList. display ( ) ;
myArrayList. removeByPos ( 1 ) ;
myArrayList. display ( ) ;
myArrayList. removeAll ( 4 ) ;
myArrayList. display ( ) ;
System. out. println ( myArrayList. size ( ) ) ;
myArrayList. add ( 0 , 1 ) ;
myArrayList. add ( 0 , 2 ) ;
myArrayList. add ( 0 , 3 ) ;
myArrayList. display ( ) ;
myArrayList. clear ( ) ;
myArrayList. display ( ) ;
System. out. println ( myArrayList. size ( ) ) ;
}
}
3.运行结果