Why doesn't java.util.HashSet have a get(Object o) method?

后端 未结 11 2198
暖寄归人
暖寄归人 2020-12-07 18:39

I\'ve seen other questions about getting objects from Set\'s based on index value and I understand why that is not possible. But I haven\'t been able to find a

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 18:54

    The reason why there is no get is simple:

    If you need to get the object X from the set is because you need something from X and you dont have the object.

    If you do not have the object then you need some means (key) to locate it. ..its name, a number what ever. Thats what maps are for right.

    map.get( "key" ) -> X!

    Sets do not have keys, you need yo traverse them to get the objects.

    So, why not add a handy get( X ) -> X

    That makes no sense right, because you have X already, purist will say.

    But now look at it as non purist, and see if you really want this:

    Say I make object Y, wich matches the equals of X, so that set.get(Y)->X. Volia, then I can access the data of X that I didn have. Say for example X has a method called get flag() and I want the result of that.

    Now look at this code.

    Y

    X = map.get( Y );

    So Y.equals( x ) true!

    but..

    Y.flag() == X.flag() = false. ( Were not they equals ?)

    So, you see, if set allowed you to get the objects like that It surely is to break the basic semantic of the equals. Later you are going to live with little clones of X all claming that they are the same when they are not.

    You need a map, to store stuff and use a key to retrieve it.

提交回复
热议问题