题目
输入:元素数组
["h","o","l","a"]
输出:具有相同顺序的数组的逗号分隔元素的字符串。
"h,o,l,a"
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class ArrayPrinterTest {
@Test
public void testString() {
String[] array=new String[]{"2","4","5","2"};
assertEquals("2,4,5,2",ArrayPrinter.printArray(array));
}
@Test
public void testInteger() {
Integer[] array=new Integer[]{2,4,5,2};
assertEquals("2,4,5,2",ArrayPrinter.printArray(array));
}
}
解题
Other:
import java.util.Arrays;
import java.util.stream.Collectors;
public class ArrayPrinter {
public static String printArray(Object[] array) {
return Arrays.stream(array).map(Object::toString).collect(Collectors.joining(","));
}
}
public class ArrayPrinter {
public static String printArray(Object[] array) {
StringBuilder sb = new StringBuilder(7);
int i = 0;
for(; i < array.length - 1; i++){
sb.append(array[i]);
sb.append(",");
}
sb.append(array[i]);
return sb.toString();
}
}
import java.util.*;
public class ArrayPrinter {
public static String printArray(Object array[]) {
String[] str = new String[array.length];
for(int i=0; i<array.length; i++) {
str[i]=String.valueOf(array[i]) ;
}
return String.join(",", str);
}
}
后记
这道题,我失败了,没想出来,被出题者诱导了,就没转过弯来。
public class ArrayPrinter {
public static String printArray(ANYTYPE array[]) {
}
}
ANYTYPE 这个任意类型让我不停的去搜相关内容,想着是不是自己不知道的知识,最后也没找到相关内容。看了别人的答案,才发现自己太傻,思维局限了,用Object就行了。
网友评论