Reputation: 537
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
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 ArrayList
s to your constructor? Why not make it take List
s, which will make it more flexible:
public PageBreak(String sheetName, List<Integer> rowPageBreaks, List<Integer> columnPageBreaks)
{
...
}
Then you have the freedom to pass it ArrayList
s, 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
Reputation: 106498
You're going to want to populate your list before you attempt to use it. Here's what's happening:
ArrayList<Integer>
.add
on that list.add
is boolean
(and consequently always returns true).boolean
result is what is interpreted, and not the list.Upvotes: 3