如何确保将在构造函数中传递的两个向量大小相等?

How to assure two vectors which will be passed in constructor size equals?

我实现了 class:

public class TableInfoGroup {
  Vector<TableInfo> tableInfoVector;
  public TableInfoGroup(Vector<String> tableNameVector, Vector<String> tableTagIdVector)
  {
    if (tableNameVector.size() != tableTagIdVector.size())
      return;//I think it's not proper to do this
    tableInfoVector = new Vector<TableInfo>();
    for(int i = 0; i < tableNameVector.size(); i++)
      tableInfoVector.add(new TableInfo(tableNameVector.get(i), tableTagIdVector.get(i)));
  }
}

那优雅怎么做?抛出异常?谢谢

就我个人而言,我会让该方法抛出一个 IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

例如:

if (tableNameVector.size() != tableTagIdVector.size())
  throw new IllegalArgumentException("tableNameVector and tableTagIdVector " +
                                     "must have the same size");

尽管 IllegalAgumentExceptionunchecked exception, I would still add it to the method's throws clause 作为文档。

让构造函数抛出异常将阻止对象被构造,我认为在这种情况下这是正确的做法。