1

我有一个带有许多重载构造函数的类。根据构造函数的不同,可能会发生异常(当其中一个startSizegrowFactor太小时)。在其他构造函数中,使用默认值并且不会发生这些异常。

是否有可能以某种方式抑制更简单的构造函数上的警告,如下所示?我不能将它们包含在 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);
}
4

1 回答 1

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];
}
于 2013-08-14T09:30:58.327 回答