Benoit Goderre
Benoit Goderre

Reputation: 537

Array List initialization displayed as boolean

I am trying to create an object with the following constructor

public PageBreak(String sheetName, ArrayList<Integer> rowPageBreaks, ArrayList<Integer> columnPageBreaks)
{
    this.sheetName = sheetName;
    this.rowPageBreaks = rowPageBreaks;
    this.columnPageBreaks = columnPageBreaks;
}

In another method, I do the following call:

pageBreaks.add(new PageBreak(teamResultSheet.getName(),
                new ArrayList<Integer>().add(teamResultSheet.getRowPageBreak()), null));

I then get the following error message: The constructor PageBreak (String, boolean, null) is undefined.

How can I create an ArrayList<Integer> on the spot?

Upvotes: 0

Views: 97

Answers (2)

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11664

While Makoto's answer is correct and explains why you are getting this error, and gives you sensible advice to create your ArrayList before you use it, you might want to know if there is any other way you can make your code more succinct.

Unlike more recent languages, such as Groovy or Kotlin, Java unfortunately does not have List literals as a language syntax. There have been some attempts to hack around this limitation; what you may have been attempting with your code is the double brace initialization idiom:

pageBreaks.add(new PageBreak(teamResultSheet.getName(),
               new ArrayList<Integer>() {{add(teamResultSheet.getRowPageBreak());}},
               null);

Although this may look cute, it does have its drawbacks, as described in the above link.

Do you really need to pass actual ArrayLists to your constructor? Why not make it take Lists, which will make it more flexible:

public PageBreak(String sheetName, List<Integer> rowPageBreaks, List<Integer> columnPageBreaks)
{
    ...
}

Then you have the freedom to pass it ArrayLists, as before, or any other kind of List:

pageBreaks.add(new PageBreak(teamResultSheet.getName(),
               Arrays.asList(teamResultSheet.getRowPageBreak()),
               null);

This looks more succinct and doesn't have the former's drawbacks; however, the list is fixed-size and immutable.

If you only want a single-element list, it's more efficient to use the following:

pageBreaks.add(new PageBreak(teamResultSheet.getName(),
               Collections.singletonList(teamResultSheet.getRowPageBreak()),
               null);

Upvotes: 1

Makoto
Makoto

Reputation: 106498

You're going to want to populate your list before you attempt to use it. Here's what's happening:

  • You instantiate a new ArrayList<Integer>.
  • You immediately call add on that list.
  • The result of add is boolean (and consequently always returns true).
  • The boolean result is what is interpreted, and not the list.

Upvotes: 3

Related Questions