Why doesn't java.util.Set have get(int index)?

前端 未结 18 1361
长情又很酷
长情又很酷 2020-11-28 18:14

I\'m sure there\'s a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get()

18条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 18:58

    Set is an interface and some of its implementation classes are HashSet, TreeSet and LinkedHashSet. It uses HashMap under the hood to store values. Because HashMap does not preserve the order, it is not possible to get value by index.

    You now must be thinking how Set is using HashMap since HashMap stores a key, value pair but the Set does not. valid question. when you add an element in Set, internally, it maintains a HashMap where the key is the element you want to enter in Set and the value is the dummy constant. Below is an internal implementation of add function. Hence, all the keys in the HashMap will have the same constant value.

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
    
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    

提交回复
热议问题