Java HashSet 包含预期值以外的值,不是预定义值

Java HashSet contains value other than the intended one, not predefined value

我看了这个论坛的回答

但是在这个论坛的回答中,选项是预定义的,对我来说不是。

我从网上读到 Table 其他城市名称可以是任何名称。

//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 可以使用什么逻辑?

提前感谢您的宝贵时间

在你的第二种情况下,你说如果城市集包含西雅图但不包含西雅图 那永远不会 return 正确。 你可以说如果城市集包含西雅图并且大小大于 1,那么如果有更多城市,那将 return 为真。

简单点,试试这个

if (citySet.size() > 1 || !citySet.contains("Seattle")) {
    Assert.fail("Expected only Seattle but found more than 1 city");
}

谢谢