我看了这个论坛的回答 Java HashSet<> : 如果HashSet中包含了指定以外的值,返回false。
然而在这个论坛的回答中,选项是预定义的,对我来说不是。
我从一个网络表格中读到,其他城市名称可以是任何东西。
/ToDo。如果集合中包含西雅图以外的任何内容,就会失败。
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。
简单点说,试试这个
if (citySet.size() > 1 || !citySet.contains("Seattle")) {
Assert.fail("Expected only Seattle but found more than 1 city");
}
谢谢