HashSet vs LinkedHashSet

后端 未结 10 2525
暗喜
暗喜 2020-11-28 18:20

What is the difference between them? I know that

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all el

10条回答
  •  醉梦人生
    2020-11-28 18:54

    HashSet don't maintain the order of insertion item
    LinkedHashSet maintain the order of insertion item

    Example

    Set set = ...;// using new HashSet<>() OR new LinkedHashSet<>()
    set.add("2");
    set.add("1");
    set.add("ab");
    for(String value : set){
       System.out.println(value);
    }  
    

    HashSet output

    1
    ab
    2
    

    LinkedHashSet output

    2
    1
    ab
    

提交回复
热议问题