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

前端 未结 18 1363
长情又很酷
长情又很酷 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:56

    If you are going to do lots of random accesses by index in a set, you can get an array view of its elements:

    Object[] arrayView = mySet.toArray();
    //do whatever you need with arrayView[i]
    

    There are two main drawbacks though:

    1. It's not memory efficient, as an array for the whole set needs to be created.
    2. If the set is modified, the view becomes obsolete.

提交回复
热议问题