Java Array 方法和使用


1、Arrays.toString():數組轉字符串

格式:Arrays.toString(數組名)

將數組轉化成字符串,此時輸出的結果是字符串類型。

import java.util.Arrays;

public class ArrayToString {
    public static void main(String[] args) {
        int arr[] = {1,2,3,4,5,6};
        
        String newArr = Arrays.toString(arr);
        System.out.println(newArr);
    }
}

運行結果:

[1, 2, 3, 4, 5, 6]

2、Arrays.copyOf(數組名,擴容后長度):數組擴容

格式:Arrays.copyOf(數組名,擴容后長度)

注意:此方法可以用於擴容,也可以用於縮容,改變其第二個參數即可。

import java.util.Arrays;

public class ArraycopyOf {
    public static void main(String[] args) {
        int arr[] = {1,2,3,4};
                
        arr = Arrays.copyOf(arr,8);

        for(int a:arr)
            System.out.print(a+" ");
    }
}

運行結果:

1 2 3 4 0 0 0 0 

3、Arrays.copy():數組的復制

格式:Arrays.copy(原數組,原數組起始位置,新數組,新數組起始位置,復制長度)

public class Arrayscopy {
    public static void main(String[] args) {
        int arr[] = {1,2,3,4};
        int[] arr1 = new int[6];
        
        System.arraycopy(arr, 0, arr1, 1, 3);
        for (int str : arr1){
            System.out.print(str+“ ”);
        }
    }
}

運行結果:

0 1 2 3 0 0 

4、Arrays.sort():數組排序

格式:Arrays.sort(數組名)

注意:只能做升序排序,不能做降序排序。

import java.util.Arrays;

public class ArraySort {
    public static void main(String[] args) {
        int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
        Arrays.sort(arr);
        
        for(int a:arr)
            System.out.print(a+" ");
    }
}

運行結果:

-9 -7 -3 -2 0 2 4 5 6 8 

5、Arrays.fill():向數組中填充元素

格式:Arrays.fill(數組名 ,開始位置 , 結束位置, 填入的值)

import java.util.Arrays;

public class ArrayFill {
    public static void main(String[] args) {
        
        int arr[] = {1,2,3,4,5,6,7,8,9,10};
        Arrays.fill(arr, 3, 6, 50);
        for(int a:arr)
            System.out.print(a+" ");
        
        System.out.println();
        
        int array[] = new int[6];
            Arrays.fill(array, 100);
            for (int i=0, n=array.length; i < n; i++) {
                System.out.print(array[i]+" ");
            }
    }
}

運行結果:

1 2 3 50 50 50 7 8 9 10 
100 100 100 100 100 100 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM