3

I have the following class:

public class Person {

    private String id;

    private Score[] scores;

    public Person() {
    }

    //getters and setters etc
}

How can I best remove all the Score objects within the scores array for this object?

Michael
  • 41,989
  • 11
  • 82
  • 128
java123999
  • 6,974
  • 36
  • 77
  • 121

4 Answers4

7

re initialize the array new Score[size] or Use Arrays.fill method.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
PrabaharanKathiresan
  • 1,099
  • 2
  • 17
  • 32
  • `scores = new Score[scores.length]` is more verbose *and* less descriptive than `Arrays.fill(scores, null)` – Michael May 26 '17 at 14:45
  • Is "verbose" bad? Freeing plus reallocating will generally support memory management better, and be faster for large arrays. "Descriptive" is a subjective term. I, at least, find the reallocation idiom perfectly descriptive, as I expect it would be for any experienced or knowledgeable Java programmer. – Lew Bloch May 26 '17 at 15:24
4

I'd use Arrays.fill and fill the array with nulls.

Arrays.fill(scores, null);
Michael
  • 41,989
  • 11
  • 82
  • 128
1

There are different options depending on what exactly you want. One of the easiest is to initialize the array to 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]
Nurjan
  • 5,889
  • 5
  • 34
  • 54
0

There's

Arrays.fill(myArray, null); Not that it does anything different than you'd do on your own (it just loops through every element and sets it to null). It's not native in that it's pure Java code that performs this, but it is a library function if maybe that's what you meant.

This of course doesn't allow you to resize the array (to zero), if that's what you meant by "empty". Array sizes are fixed, so if you want the "new" array to have different dimensions you're best to just reassign the reference to a new array as the other answers demonstrate. Better yet, use a List type like an ArrayList which can have variable size.

  • "This of course doesn't allow you to resize the array (to zero)" - Having a zero-sized array is pointless. It will never be useful for anything. – Michael May 26 '17 at 14:44