-3

I have a class like:

public class TemplateFileResponse {
    private String path;
    private List<FileView> children;
}

I want to create an instance and set children is empty array. so what is the best way to do it?

5
  • 3
    Empty list you mean? Add a constructor Commented Jan 2, 2020 at 17:15
  • 1
    An array is one thing e.g. FileView[]. A List is another different thing. Commented Jan 2, 2020 at 17:16
  • See Oracle tutorial, docs.oracle.com/javase/tutorial/java/javaOO/initial.html Commented Jan 2, 2020 at 17:17
  • You can create like this private List<FileView> children = new ArrayList<>(); Commented Jan 2, 2020 at 17:18
  • TemplateFileResponse t = new TemplateFileResponse(); t.setChildren(new ArrayList<>()); Commented Jan 2, 2020 at 17:28

1 Answer 1

-1

You can create an empty list with the new operator:

public class TemplateFileResponse {
    private String path;
    private List<FileView> children = new ArrayList<>();
}

You may also want to initialize the path field, either in a constructor or inline, because otherwise it will be initialized to null by default.

I suggest that you read a tutorial about Java classes, constructors, methods, and instantiating objects to understand how all of this works.

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

4 Comments

@Michael I'm not confused. My wording is just poor and incomplete. Presumably inline intialization for path doesn't make any sense.
@Michael Sure, the path field could be left uninitialized at all. But then there would be no point in having it.
@Michael Feel free to write your own answer or make edit suggestions directly.
Alright, I have

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.