-2

I have a custom object Point and its constructor's parameters are given as Point(int x, int y).

I want an array of ten distinct point, and each Point should be initialized to (13, 27) position, using a constructor.

Point[] points = new Point[10];
for (Point point : points) {
    point = new Point(13, 27);
}

I don't like the fact that in between the first line and the second line I have an array of nulls.

Can I somehow declare and initialize an array of references with my constructor, using one-liner?

The following works but we can see the problems with it:

Point[] points = new Point[] {
    new Point(10, 10),
    new Point(10, 10),
    new Point(10, 10),
    /// <7 more points omitted>
};

I am also wondering about a solution with List such as ArrayList.

In C++ I would do e.g.: std::vector<Point> points{10, Point{13, 27}};.

Edit: I need my array to hold references to 10 distinct (but equal) Point objects.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
weno
  • 804
  • 8
  • 17

2 Answers2

4

You could use java streams to produce your array:

Point[] points = Stream.generate(() -> new Point(13,27)).limit(10).toArray(Point[]::new);
Jakob Em
  • 1,032
  • 9
  • 19
1

Edit: You require 10 distinct objects. You may go with Jakob Em’s stream solution or the one by Govi S. Or if you can live with the array holding null values temporarily:

    Point[] points = new Point[10];
    Arrays.setAll(points, index -> new Point(13, 27));

To me holding nulls until initialized doesn’t appear to be that bad, and behind the scenes that happens in the stream solutions too.

My original answer gave you an array of 10 references to one and the same Point object. It may not be the code one would immediately expect to see for the task, but I think it’s well readable:

    Point[] points = Collections.nCopies(10, new Point(13, 27)).toArray(new Point[0]);

Since Java 11 a bit clearer still:

    Point[] points = Collections.nCopies(10, new Point(13, 27)).toArray(Point[]::new);

It also seems to me to be similar to your C++ way.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161