一、数组的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();}}