简体   繁体   English

用数字字段对2D数组字符串进行排序

[英]Sorting 2D array String with number fields

I think many people have come across this problem, You have a 2D array consisting of a String conponent and an Interger. 我认为很多人都遇到过这个问题,您有一个由String组件和Interger组成的2D数组。 ex. 恩。

    `String[][] data = {{"Name1","5"}, {"Name2","10"},{"Name3","1"}, {"Name4","3"}};`

Now you want to sort that 2D array by the integer (in this case the players score), however you want the matching name to be moved along with the players score. 现在,您要按整数对2D数组排序(在本例中为玩家得分),但是您希望将匹配名称随玩家得分一起移动。 This is what i've got, but the result is far away from what it is suppose to be. 这就是我所得到的,但是结果与预期的结果相去甚远。

    private void sort(){
    boolean sort;
    int current, next;
    do{
            sort = true;
            for (int i = 0; i < data.length - 1; i++){
                if (data[i][1] !=null && data[i+1][1] != null){
                    current = Integer.parseInt(data[i][1]);
                    next = Integer.parseInt(data[i+1][1]);
                        if(current > next){
                                String temp = "";
                                data[i][1] = Integer.toString(next); 
                                data[i+1][1] = Integer.toString(current);
                                data[i][0] = temp;
                                data[i][0] = data[i+1][1];
                                data[i+1][0] = temp;       
                                sort = false;
                        }
                }

            }

    }while(!sort);
}

If you ask why people would use a common 2D array, it is because in JFRAME, a JTable needs an 2D array for the data. 如果您问为什么人们会使用通用2D数组,那是因为在JFRAME中,JTable需要一个2D数组来存储数据。

You can write a special Comparator, wich can compare eg {"Name1","5"} and {"Name2","10"} But I recomment to change your data structure. 您可以编写一个特殊的比较器,可以比较例如{"Name1","5"}{"Name2","10"}但我建议您更改数据结构。

I would create a type caonatining name and int 我会创建一个类型caonatining 名称int

class NameNum{
   String name;
   int number;
}

and store them in a 1D Array 并将它们存储在一维数组中

NameNum[] data 

Implement a compare method and than simply use Arrays.sort(..) to sort the array. 实现一个compare方法,而不是简单地使用Arrays.sort(..)对数组进行排序。

First of all: your array elements do not consist of a string and an integer since in: 首先:由于以下原因,您的数组元素不由字符串和整数组成:

{ "Name1", "5" }

"5" is not an Integer but a String . "5"不是Integer而是String

Provided that you do not care about equality, the solution here is to create a wrapper object over this tuple, make it implement Comparable of itself and use a SortedSet . 如果您不关心相等性,则此处的解决方案是在该元组上创建包装对象,使其实现自己的Comparable并使用SortedSet You will have to reverse it for display, and fortunately the JDK also has builtin methods for that. 您将不得不反转它以进行显示,幸运的是,JDK也为此提供了内置方法。

Sample code: 样例代码:

private static final String[][] data = {
    { "Name1", "5" },
    { "Name2", "10" },
    { "Name3", "1" },
    { "Name4", "3" }
};

private static final class Score
    implements Comparable<Score>
{
    private final String name;
    private final int score;

    private Score(final String name, final String scoreAsString)
    {
        this.name = name;
        // NOTE: this can throw an (unchecked) NumberFormatException,
        // but this code assumes that it never does
        score = Integer.parseInt(scoreAsString);
    }

    @Override
    public int compareTo(final Score o)
    {
        final int ret = score - o.score;
        return ret != 0 ? ret : name.compareTo(o.name);
    }

    // Print results nicely ;)
    @Override
    public String toString()
    {
        return "Name: " + name + ", score: " + score;
    }
}

public static void main(final String... args)
{
    final SortedSet<Score> set = new TreeSet<Score>();
    Score score;

    for (final String[] raw: data) {
        score = new Score(raw[0], raw[1]);
        set.add(score);
    }

    // Build a List from that Set...
    final List<Score> scoreList = new ArrayList<Score>(set);

    // Reverse it...
    Collections.reverse(scoreList);

    // Print results
    for (final Score s: scoreList)
        System.out.println(s);
}

Copy/paste the above code in a class, run it: you will see that it does what is intended. 将以上代码复制/粘贴到一个类中,运行它:您将看到它可以完成预期的工作。

IMPORTANT NOTE : yes, this custom class does not override equals() / hashCode() ; 重要提示 :是的,这个定制类没有重载equals() / hashCode() ; this is not an oversight: as only comparison is required here (since a SortedSet is used), there was no reason for implementing them at all. 这不是疏忽:因为这里只需要比较(因为使用了SortedSet ),所以根本没有理由实现它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM