Copy //by overloading method
static String toString( boolean [] a)
static String toString( byte [] a)
static String toString( char [] a)
static String toString( short [] a)
static String toString( int [] a)
static String toString( long [] a)
static String toString( float [] a)
static String toString( double [] a)
static String toString( Object [] a)
2. Copy Array - copyOf(), copyOfRange()
Copy int [] arr = { 0 , 1 , 2 , 3 , 4 };
int [] arr2 = Arrays . copyOf (arr , arr . length ); //arr2 = [0,1,2,3,4]
int [] arr3 = Arrays . copyOf (arr , 3 ); //arr3 = [0,1,2]
int [] arr4 = Arrays . copyOf (arr , 7 ); //arr4 = [0,1,2,3,4,0,0]
int [] arr5 = Arrays . copyOfRange (arr , 2 , 4 ); //arr5 = [2,3], does not including 4
int [] arr6 = Arrays . copyOfRange (arr , 0 , 7 ); //arr6 = [0,1,2,3,4,0,0]
3. Fill out Array - fill( ), setAll()
- fill( ): Fill out with specific vaue(number,...)
- setAll() : Fill out with Lambda.
Copy int [] arr = new int [ 5 ];
Arrays . fill (arr , 9 ); //arr=[9,9,9,9,9]
// 1 <= x < 6
//arr=[1,5,2,1,1]
Arrays . setAll (arr , (i) -> ( int )( Math . random () * 5 ) + 1 );
4. Sort and Serarch Array - sort(), binarySearch()
- binarySearch() : Only when array is sorted. So, you should sort the array first.
Copy int [] arr = { 3 , 2 , 0 , 1 , 4 };
int idx = Arrays . binarySearch (arr , 2 ); //idx=-5 <- wrong result.
Arrays . sort (arr);
System . out . println ( Arrays . toString (arr)); //[0,1,2,3,4]
int idx = Arrays . binarySearch (arr , 2 ); //idx=2 <-correct result.
5. Print Multiple-dimensional Array - deepToString( )
Copy int [] arr = { 0 , 1 , 2 , 3 , 4 };
int [][] arr2D = {{ 11 , 12 } , { 21 , 22 };
System . out . println ( Arrays . toString (arr));
System . out . println ( Arrays . deepToString (arr2D)); //[[11,12],[21,22]]
6. Compare Multiple-dimensional Array - deepEquals( )
Copy String [][] str2D = new String [][]{{ "aaa" , "bbb" } , { "AAA" , "BBB" }};
String [][] str2D2 = new String [][]{{ "aaa" , "bbb" } , { "AAA" , "BBB" }};
System . out . println ( Arrays . equals (str2D , str2D2)); //false
System . out . println ( Arrays . deepEquals (str2D , str2D2)); //true
7. Casting Array to List - asList(Object ...a)
- asList(Object...a) : Mutable parameter. The number of parameter is not defined.
- List is for read data.
Copy List list = Arrays . asList ( new Integer []{ 1 , 2 , 3 , 4 , 5 });
List list = Arrays . asList ( 1 , 2 , 3 , 4 , 5 );
//지원하지 않는 기능이기 때문에.
list . add ( 6 ); //UnsupportedOperationException 예외 발생
List list = new ArrayList( Arrays . asList( 1 , 2 , 3 , 4 , 5 )) ;
Copy int [] iArr = { 100 , 95 , 80 , 70 , 60 };
System . out . println (iArr); //[I@14318bb] 같은 형식의 문자열 출력
char [] chArr = { 'a' , 'b' , 'c' , 'd' };
System . out . println (chArr); //abcd 출력
배열 출력 - Arrays.toString() 이용(많이 사용)
: iArr의 배열 값들을 String으로 바꿔주고 이 String을 출력한다. 한번에 출력되기 때문에 편하다.
Copy System . out . println ( Arrays . toString (iArr));