0

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 new 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?

2 Answers 2

5

Use a TreeSet with a custom comparator.

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Obviously it's possible to write a wrapped list that keeps track of the ten highest elements, but in all honesty, unless there was a serious performance issue, sticking with the built-in libraries is the way to go!
Brilliant, thanks. I knew there had to be a better way than arrays!
3

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

2 Comments

I guess you mean Arrays.binarySearch(), Collections.binarySearch works on Lists, not Arrays
Although I think he should use a List in the first place, insertions are easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.