package com.heima.stringbuffer;
public class Demo3_Arrays2String {
/**
* @param args
* (1)模拟Arrays.toString(int[] arr);方法,自己封装一个public static String toString(int[] arr);
(2)如果int类型数组arr为null,toString方法返回字符串"null"
(3)如果int类型数组arr长度为0,toString方法返回字符串"[]"
(4)如果int类型数组arr的内容为{1,2,3,4,5},toString方法返回字符串"[1, 2, 3, 4, 5]"
*/
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
String s = toString(arr);
System.out.println(s);
int[] arr1 = null;
String s1 = toString(arr1);
System.out.println(s1);
int[] arr2 = new int[0];
String s2 = toString(arr2);
System.out.println(s2);
}
public static String toString(int[] arr) {
if (arr == null) {
return "null";
}
if (arr.length == 0) {
return "[]";
}
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
if (i != arr.length-1) {
sb.append(arr[i]).append(",");
}else {
sb.append(arr[i]);
}
}
sb.append("]");
return sb.toString();
}
} |
|