Artur
Artur

Reputation: 130

How to print all non null elements of an array using Array.toString()

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.

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.

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]

Thanks a lot!

Upvotes: 1

Views: 5651

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

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.

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.

Examples

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));

Upvotes: 2

libik
libik

Reputation: 23029

If you want a dynamic array in Java, the best way is to learn how to use lists :

List<Integer> integers = new ArrayList<Integer>();

It prints only as many numbers as you put into it.

If you dont want to rewrite your program, this is also solution :

    Integer[]x = new Integer[50];
    List<Integer> integers = new ArrayList<Integer>();        
    integers = new ArrayList<Integer>(Arrays.asList(x));

Upvotes: 2

Mureinik
Mureinik

Reputation: 311438

It would be much easier to store the user's input in an ArrayList, and then just print myArryList.toString().

Upvotes: 4

Related Questions