How do I clear a primitive array?

I have the following class:

public class Person {

    private String id;

    private Score[] scores;

    public Person() {
    }

    //getters and setters etc
}

      

What's the best way to remove all objects Score

in the score array for that object?

+3


source to share


4 answers


reinitialize the array new Score[size]

or use a method Arrays.fill

.



+7


source


I would use Arrays.fill

and fill the array with zeros.



Arrays.fill(scores, null);

      

+4


source


There are different options depending on what exactly you want. One of the simplest is to initialize an array for a new array:

 int[] scores = new Scores[]{1,2,3};
 System.out.println("scores before: " + Arrays.toString(scores));
 scores = new Scores[scores.length];
 System.out.println("scores after: " + Arrays.toString(scores));

      

Output:

scores before: [1, 2, 3]
scores after: [0, 0, 0]

      

+1


source


In the same place

Arrays.fill (myArray, null); Not that it does anything different than what you did yourself (it just loops through each element and sets it to null). It's not native in that it's pure Java code that does this, but it's a library function, maybe that's what you meant.

This, of course, does not allow the array to be resized (down to zero) if that's what you mean by "empty". The array sizes are fixed, so if you want the "new" array to have different sizes, your best bet is to reassign the reference to the new array, as other answers show. Better yet, use a List type like ArrayList, which can be variable in size.

0


source







All Articles