Storing arrays in Set and avoiding duplicates

前端 未结 5 1776
你的背包
你的背包 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:29

    The "better way" is to use collections. Use a List instead of a String[]:

    Set> boog = //...
    boog.add(Arrays.asList("a", "b", "c"));
    boog.add(Arrays.asList("a", "b", "c"));
    boog.add(Arrays.asList("a", "b", "d"));
    
    System.out.println(boog.size()); // 2
    

    Edit

    If you absolutely needed to use arrays as keys, you could build a transparent wrapper around each key and put that in the map. Some libraries help you with that. For example, here's how you could do a Set using Trove:

    Set boog = new TCustomHashSet(new ArrayHashingStrategy());
    
    boog.add(new String[]{"a", "b", "c"});
    boog.add(new String[]{"a", "b", "c"});
    boog.add(new String[]{"a", "b", "d"});
    
    System.out.println(boog.size()); // 2
    
    //...
    public class ArrayHashingStrategy extends HashingStrategy {
    
       public int computeHashCode(Object[] array) {
          return Arrays.hashCode(array);
       }
    
       public boolean equals(Object[] arr1, Object[] arr2) {
          return Arrays.equals(arr1, arr2);
       }
    }        
    

提交回复
热议问题