I know that it is necessary to do so that the mutable object does not return and the encapsulation is not lost:

public class CubeWarehouse{ private Set<Cube> cubeSet = new HashSet<>; public Set<Cube> getWareHouse(){ return Collections.unmodifiableSet(cubeSet); } } 

Do we have to do this if we return an array:

 public Cube[] getArray(){ return Collections.unmodifiableSet(cubeSet).toArray(new Cube[0]); } 

    1 answer 1

    There is no need to copy the Set in the second case, since toArray(T[]) will also make a copy.

    Https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray (T []) says:

    Note that toArray (new Object [0]) is identical to function toArray ().

    And at https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray () :

    Modify the returned array.

    • one
      you bring the dock to the wrong method that is invoked, toArray(T[] array) will also be safe here, only it does not give such guarantees) - etki
    • Yes, wrong, thanks. But I didn’t quite understand the lack of guarantees. Set will also be copied when calling toArray(new Cube[0]) . The only thing that will not create a new array is if the entire Set is placed in the array passed by the parameter. - Anton Maximov