我看了这个论坛的答案Java HashSet<> : Return false if HashSet contains values other than specified
但是,在此论坛答案中,选项是预定义的,但对我来说不是。
我从Web表格中读取,另一个城市名称可以是任何名称。
// ToDo:如果set包含非Seattle的任何内容,则使其失败
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。
您可以说,如果城市集包含Seattle并且大小大于1,那么在有更多城市的情况下将返回true。