开发者

Is there a data structure for a list ordered by value?

I've got a JTable which shows the top 10 scores of a game. The data structure looks like the following:

    // {Position, Name, Score}
Object[][] data = {
    {1, "-", 0},
    {2, "-", 0},
    {3, "-", 0},
    {4, "-", 0},
    {5, "-", 0},
    {6, "-", 0},
    {7, "-", 0},
    {8, "-", 0},
    {9, "-", 0},
    {10, "-", 0}
};

I want to be able to add a ne开发者_运维问答w score to this array in the correct order (so if it was the 3rd highest, it would be put at index 2). I'll then truncate this list down to the top 10 again and update the table.

I know this is trivial to do by looping through and checking, but I'd like to know if there is an appropriate data structure that is better suited for data ordered by a value? Or is the simple two-dimensional array the only/best?


Use a TreeSet with a custom comparator.

Also, you should not work with Multi-dimensional arrays, use Maps (Name -> Score) or custom Objects


Hey, if your array is sorted, u can use the Collections.binarySearch() or Arrays.binarySearch() method to guide u at what index to make the insertion. The way these method work is to make a binary search after an existing element, and if the element cannot be found in the collection it will return a value related to the insertion point.
More info here Collections.binarySearch

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜