1

I was practicing the visitor pattern. And I found something interesting that the program created a new ArrayList inside the constructor, which confuses me.

For example:

class Computer implements ComputerPart
{
List<ComputerPart> parts;   

public Computer(){
  parts = new ArrayList<>(List.of(
    new Mouse(),
    new Keyboard(),
    new Monitor()
));
}

Is that equals to:

class Computer implements ComputerPart
{
List<ComputerPart> parts = new ArrayList<>(List.of(
  new Mouse(),
  new Keyboard(),
  new Monitor()
));


public Computer(){
  
} 

Does that mean when creating the new Computer, then it will have a new ArrayList of the Keyboard, Mouse, and Monitor? Any help is highly appreciated.

2
  • 6
    Could you precise what confuses you? The one initializes the list inline, the other initializes it in the constructor. Each is done when a new instance is created. Commented Jul 17, 2020 at 0:55
  • 2
    The effect is the same. Commented Jul 17, 2020 at 1:32

1 Answer 1

2

The result is the same.

Although not needed here, the advantage of initializing the field in the constructor is:

  • Can use constructor parameter values in the list values.
  • Can use separate statements to calculate (complex) list values.
  • Multiple constructors can initialize the value differently.

The advantage of initializing the field in the field declaration is:

  • Keeping field type, name, and initial value all in one place.
  • Code is more concise, e.g. no need to write default constructor.

For the code in the question, it can be done either way. Inline would be more concise, but using constructor is not wrong, just another way of doing it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.