【Java】实现数组转化成字符串的方法

toString方法

Java中的Array库中本身自带toString方法,可以使数组转化成字符串

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr1 = {1,2,3};
        int[] arr2 = null;
        int[] arr3 = {};
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
        System.out.println(Arrays.toString(arr3));
    }
}

最终运行结果为

[1, 2, 3]
null
[]

Process finished with exit code 0

可见,若数组有内容,则直接打印数组

            若数组为空,则打印"[]"

            若数组指向null,则直接打印null 

编写数组转化成字符串的方法

为了实现和toSTring同样的功能,我们编写了以下代码

import java.util.Arrays;

public class Main {
    public static String myToString(int[] arr){
        //注意:当数组是null时,若取长度会发生空指针异常
        if(arr == null){
            return "null";
        }
        if(arr.length == 0){
            return "[]";
        }
        String ret = "[";
        for (int i = 0; i < arr.length; i++) {
            ret += arr[i];
            if(i < arr.length - 1){
                ret += ", ";
            }else {
                ret += "]";
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        int[] arr1 = {1,2,3};
        int[] arr2 = null;
        int[] arr3 = {};
        System.out.println(myToString(arr1));
        System.out.println(Arrays.toString(arr1));
        System.out.println(myToString(arr2));
        System.out.println(Arrays.toString(arr2));
        System.out.println(myToString(arr3));
        System.out.println(Arrays.toString(arr3));
    }
}

最终打印结果为

[1, 2, 3]
[1, 2, 3]
null
null
[]
[]

Process finished with exit code 0

你可能感兴趣的:(#,JavaSE,Java,java,开发语言)