我查看了这个论坛的答案Java HashSet<> : Return false if HashSet contains values other than specified
但是在这个论坛答案中,选项是预定义的,对我来说不是。
我从网络表中读取,其他城市名称可以是任何名称。
//ToDo:如果set包含西雅图以外的任何内容,则使其失败
public void cityTest() {
Set<String> citySet = new HashSet<>();
citySet.add("Seattle");
citySet.add("Boston");
//Case 1: Check size and if it is more than 1 we know we got more than 1 city name
if (citySet.size() > 1) {
Assert.fail("Expected only Seattle but found more than 1 city");
}
//Case 2: See if the set contains any other city name than Seattle
if (citySet.contains("Seattle") && (!(citySet.contains("Seattle")))) { // This does not work
Assert.fail("Expected only Seattle but found more than 1 city");
}
}
}
问题:案例 2 可以使用什么逻辑?
预先感谢您的宝贵时间
最佳答案
在第二种情况下,您所说的城市集是否包含西雅图并且不包含西雅图 那永远不会返回 true。 你可以说,如果城市集包含西雅图并且大小大于 1,如果有更多城市,则返回 true。
关于Java HashSet 包含预期值以外的值,而不是预定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61619443/