一、數組的2種定義方式
數據類型 []? 數組名稱 =?
new
?數據類型[數組長度];
這里 [] 可以放在數組名稱的前面,也可以放在數組名稱的后面,一般放在名稱的前面
數據類型 [] 數組名稱 = {數組元素
1
,數組元素
2
,......}
這種方式聲明數組的同時直接給定了數組的元素,數組的大小有給定的數組元素個數決定
public class ArrayStruct {public static void main(String[] args) { // int[] nums = new int[10]; // int nums[] = new int[10]; // nums = initArray( nums );// int[] nums = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };int nums[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };printArray( nums );}public static int[] initArray( int[] arr ){for( int i = 0; i < arr.length; i++ ){arr[i] = i * 10;}return arr;}public static void printArray( int[] arr ){for( int i = 0; i < arr.length; i++ ){System.out.print( arr[i] + "\t" );}System.out.println();} }
?二,實現一個自定義的數組結構,包含以下基本操作:
>插入數據
>刪除數據
>查找數據
>遍歷數據等
?
package com.ghostwu;class MyDefineArrayStruct {private int[] arr;private int curLen;private int length;public MyDefineArrayStruct(){curLen = 0;length = 30;arr = new int[length];}public MyDefineArrayStruct( int _length ) {curLen = 0;length = _length;arr = new int[length];}public int length (){return curLen;}public void print(){for( int i = 0; i < curLen; i++ ){System.out.print( arr[i] + "\t" );}System.out.println( );}public boolean add( int _value ){if( curLen >= length ){return false;}else{arr[curLen++] = _value;}return true;}public int getItem( int _index ){if( _index < 0 || _index > curLen ) {System.out.println( "數組下標越界" );}return arr[_index];}public int find( int _value ){int i;for( i = 0; i < curLen; i++ ){if( arr[i] == _value ){break;}}if( i == curLen ) {return -1;}return i;}public boolean delItem( int _value ){int res = find( _value );if( res == -1 ) return false;else {if( res == curLen - 1 ) {curLen--;}else {for( int i = res; i < curLen - 1; i++ ){arr[i] = arr[i+1];}curLen--;} }return true;}public boolean updateItem( int _oldValue, int _newValue ){int res = find( _oldValue );if( res == -1 ){System.out.println( "數組中不存在" + _oldValue );return false;}else{arr[res] = _newValue;return true;}}}public class SelfDefineArrayStruct {public static void main(String[] args) {MyDefineArrayStruct arr = new MyDefineArrayStruct( 10 );arr.print();arr.add( 10 );arr.add( 20 );arr.add( 30 );arr.add( 40 ); arr.add( 100 );arr.print();arr.delItem( 10 );arr.print();System.out.println( arr.length() );arr.delItem( 20 );System.out.println( arr.length() );arr.updateItem( 30, 300 );arr.updateItem( 40, 400 );System.out.println( arr.length() );arr.print();}}
?