Storing arrays in Set and avoiding duplicates

前端 未结 5 1791
你的背包
你的背包 2020-12-24 06:09
HashSet boog = new HashSet();
boog.add(new String[]{\"a\", \"b\", \"c\"});
boog.add(new String[]{\"a\", \"b\", \"c\"});
boog.add(new          


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 06:51

    hashCode() of arrays uses the default implementation, which doesn't take into account the elements, and you can't change that.

    You can use a List instead, with a hashCode() calculated based on the hashcodes of its elements. ArrayList (as most implementations) uses such function.


    Alternatively (but less preferable, unless you are forced somehow to use arrays), you can use a 'special' HashSet where instead of invoking key.hashCode() invoke Arrays.hashCode(array). To implement that extend HashMap and then use Collections.newSetFromMap(map)

提交回复
热议问题