如何使用Array.toString()打印数组的所有非null元素 [英] How to print all non null elements of an array using Array.toString()
问题描述
所以我需要打印出一个整数数组.问题是,当用户输入要处理和排序的数字时,我不知道用户将输入多少个数字.唯一的规则是用户只能输入少于10000个数字.
So I need to print out an array of integers. The problem is that when user enters the numbers to be processed and sorted, I do not know how many numbers there will be entered by the user. The only rule to that is that user can enter only less than 10000 numbers.
因此,我制作了一个可以容纳10000个数字的数组,但是如果用户在该数组中输入的数字少于10000个,那么 Array.toString()
函数将打印出所有内容,甚至包括空格.
So I made an array which can hold 10000 numbers but if user enters less than 10000 numbers into the array then Array.toString()
function prints out everything, even the empty spaces.
是否有任何方法可以绕过该方法,或者是否有其他方法可以在一行中输出一个数组,以格式化输出,使其看起来像这样: [1、2、3、4、5、6]
Is there any way to bypass that or are there any other methods for outputting an array in one line that would format it the output to look like this: [1, 2, 3, 4, 5, 6]
非常感谢!
推荐答案
ArrayList< T>
(对于泛型,可选地为< T>
).是一个数组,如果有更多输入可用,它会动态添加更多内存.将元素添加到此类列表的摊销成本为 O(1),但它提供了一种方便的方式来处理输入.
An ArrayList<T>
(optionally <T>
for generics). Is an array that dynamically adds more memory if more input comes available. The amortized cost of adding an element to such list is O(1), but it offers a convenient way to process input.
要回答您的问题,正如@Mureinik已经回答的那样,您可以使用 ArrayList.toString()
将列表转换为文本表示形式.
To answer your question, as @Mureinik already answered you then can use ArrayList.toString()
to convert the list to a textual representation.
要回答您的真实问题,您可以执行以下操作:
To answer your real question, you can do the following:
public static<T> String toStringArrayNonNulls (T[] data) {
StringBuilder sb = new StringBuilder();
sb.append("[");
int n = data.length;
int i = 0;
for(; i < n; i++) {
if(data[i] != null) {
sb.append(data[i].toString());
break;
}
}
for(; i < n; i++) {
if(data[i] != null) {
sb.append(",");
sb.append(data[i].toString());
}
}
sb.append("]");
return sb.toString();
}
然后使用所需的任何类型的数组调用该方法.
And call that method with any type of array you want.
示例
String[] names = new String[] {"Alice",null,"Charly","David",null,null};
System.out.println(toStringArrayNonNulls(names));
Integer[] primes = new Integer[] {2,3,null,null,11};
System.out.println(toStringArrayNonNulls(primes));
Object[] namesAndPrimes = new Integer[] {"Alice",2,null,3,null,"Charly",null,11};
System.out.println(toStringArrayNonNulls(namesAndPrimes));
这篇关于如何使用Array.toString()打印数组的所有非null元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!