我有一个包含许多重载构造函数的类。根据构造函数,可能会发生异常(当startSize
或growFactor
太小时)。在其他构造函数中,使用默认值,并且不会发生这些异常。
是否有可能以某种方式抑制更简单的构造函数上的警告,如下所示?我不能将它们包含在try-catch块中,因为重载的构造函数调用必须是第一次调用。
private static final int DEFAULT_STARTSIZE = 50;
private static final int DEFAULT_SCALEFACTOR = 2;
public LinkedArrayList()
{
this(LinkedArrayList.DEFAULT_STARTSIZE, LinkedArrayList.DEFAULT_SCALEFACTOR);
}
public LinkedArrayList(T... startCollection)
{
this(LinkedArrayList.DEFAULT_STARTSIZE, LinkedArrayList.DEFAULT_SCALEFACTOR, startCollection);
}
public LinkedArrayList(int startSize) throws InitialSizeTooSmallException
{
this(startSize, LinkedArrayList.DEFAULT_SCALEFACTOR);
}
public LinkedArrayList(int startSize, T... startCollection) throws InitialSizeTooSmallException
{
this(startSize, LinkedArrayList.DEFAULT_SCALEFACTOR, startCollection);
}
public LinkedArrayList(int startSize, int growFactor) throws InitialSizeTooSmallException, InitialGrowFactorTooSmallException
{
if (startSize < 1)
throw new InitialSizeTooSmallException();
if (growFactor < 1)
throw new InitialGrowFactorTooSmallException();
this.data = new DLNodeList<T>(startSize, growFactor);
}
public LinkedArrayList(int startSize, int growFactor, T... startCollection) throws InitialSizeTooSmallException, InitialGrowFactorTooSmallException
{
this(startSize, growFactor);
for (T item : startCollection)
this.add(item);
}
答案 0 :(得分:2)
此问题经常出现。不要在没有消息的情况下抛出特定异常,而应该使用正确的消息抛出IllegalArgumentException
"Initial size is too small :" + startSize
。
有关参考,请参阅ArrayList
初始化:
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}