Iterate to find a Map entry at an index?

前端 未结 4 1856
小鲜肉
小鲜肉 2020-12-20 13:35

I have a LinkedHashMap. I want to get the Foo at index N. Is there a better way of doing this besides iterating until I find it?:

int target = N;
int index =         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 14:09

    A simplification of @Mark's solution... You only need the values, so each time you change a value in the foos Map, also update an array.

    Map foos =;
    Foo[] fooValues = {};
    
    foos.put(foos.name(), foo);
    fooValues = foos.values().toArray(new Foo[foos.size()]);
    
    // later
    Foo foo = fooValues[N];
    

提交回复
热议问题