数组工具类Arrays

  • Arrays.toString()方法可以打印出[ ]
//需求:int[] ages = {1, 3, 5, 7, 9};打印输出"[1, 3, 5, 7, 9]"
public class ArrayPrintDemo {
    public static void main(String[] args) {
        int[] ages = {1, 3, 5, 7, 9};
        String ret = "[";
        for (int i = 0; i < ages.length; i++) {
            //最后一个元素不拼接逗号
            if (i == ages.length - 1){
                ret = ret + ages[i] + "]";
            }else {
                ret = ret + ages[i] + ",";
            }
        }
        System.out.println(ret);
        //用Arrays.toString()方法实现
        String s = Arrays.toString(ages);
        System.out.println(s);
    }
}