gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:29:38 26 4
gpt4 key购买 nike

我实现了一个类:

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 , 我仍然会把它添加到方法的 throws clause 中作为文档。

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

关于java - 如何确保将在构造函数中传递的两个 vector 大小相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30120386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com