-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.

7
  • 1
    Does this answer your question? How to initialize all the elements of an array to any specific value in java Commented Jun 27, 2020 at 11:36
  • @SabareeshMuralidharan Unfortunately I am not dealing with primitives. Commented Jun 27, 2020 at 11:37
  • 2
    Can this help Point[] points = new Point[10]; Arrays.fill(points, new Point(13, 27)); Commented Jun 27, 2020 at 11:38
  • 1
    @Joni Repetition? Commented Jun 27, 2020 at 11:55
  • 1
    Do you require 10 distinct Point objects (so you may modify each independently later), or will 10 references to the same Point object do? Commented Jun 27, 2020 at 12:04

2 Answers 2

4

You could use java streams to produce your array:

Point[] points = Stream.generate(() -> new Point(13,27)).limit(10).toArray(Point[]::new);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.