使用ArrayList作为构造函数的参数
我试图为一个接受ArrayList(包含整数)作为其参数之一的类编写构造函数。 稍后再实例化这个类时,我会传递一个适当的,预先填充的值列表,所以我不想在构造函数中创建一个空列表。
不幸的是,当我尝试编译下面的代码时,Java吐出了五个错误,都与第23行有关(我的构造函数的函数定义)。 任何意见,将不胜感激:
/*
* SumGenerator
*
* @author James Scholes
*/
import java.util.ArrayList;
import java.util.Random;
public class SumGenerator
{
// Some initial variables
public int timesTable;
public int multiple;
/*
* Constructor
*
* @param timesTable(int): The times table to use for sum generation
* @param limit(int): The highest multiple to use in sum generation
* @param previousMultiples(ArrayList<Integer>): The previously used multiples to avoid sum duplication
*/
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
{
this.timesTable = timesTable;
Random randomGenerator = new Random();
// Create a list to store our multiples
ArrayList<Integer> multiples = new ArrayList<Integer>();
// and add our multiples to it, only if
// they haven't been used before
for(int i = timesTable; i <= limit; i++)
{
if(previousMultiples.contains(i))
{
continue;
}
else
{
multiples.add(i);
}
}
this.multiple = multiples.get(randomGenerator.nextInt(multiples.size()));
}
}
SumGenerator.java:23: error: ')' expected
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
^
SumGenerator.java:23: error: illegal start of type
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
^
SumGenerator.java:23: error: <identifier> expected
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
^
SumGenerator.java:23: error: ';' expected
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
^
SumGenerator.java:23: error: <identifier> expected
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
^
5 errors
您无法提供Java中参数的默认值: int limit = 10
。 为了解决问题,提供重载的构造函数。 一个没有limit
,并将提供另一个默认值。
public SumGenerator(int timesTable, ArrayList<Integer> previousMultiples)
{
this(timesTable, 10, previousMultiples);
}
public SumGenerator(int timesTable, int limit, ArrayList<Integer> previousMultiples)
{
// Your constructor here.
}
Java不支持默认参数。
public SumGenerator(int timesTable, int limit = 10, ArrayList<Integer> previousMultiples)
卸下= 10
在int limit = 10
。 Java不支持构造函数或方法参数的默认值。
上一篇: Using an ArrayList as Parameter of Constructor
下一篇: Android: How to set a default value for an argument variable