Frage

I have a class with a number of overloaded constructors. Depending on the constructor, an exception may occur (when either startSize or growFactor is too small). In other constructors, default values are used and these exceptions will not occur.

Is it possible to somehow suppress the warnings on the simpler constructors, as displayed below? I can't enclose them in a try-catch block since overloaded constructor calls have to be the first call.

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);
}
War es hilfreich?

Lösung

This problem appears rather often. Instead of throwing specific exception with no message you should throw IllegalArgumentException with correct message like "Initial size is too small :" + startSize.

For the reference see ArrayList initialization:

public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top