简体   繁体   English

用Doubles Java对数组排序

[英]Sorting an Array with Doubles Java

I'm reading a text file into a 2D array. 我正在将文本文件读取为2D数组。 The first column ( the one I'm sorting on) is almost all Doubles. 第一列(我正在排序的列)几乎是Doubles。 As you all probably know, it sorts 1.1 1.6 25.6 6.4, how can I fix this? 大家都知道,它排序为1.1 1.6 25.6 6.4,我该如何解决?

import java.io.*;
import java.util.*;

public class Sort {

    public static void main(final String[] args) throws FileNotFoundException {
        FileOutputStream out = new FileOutputStream("/Users/evanlivingston/2d.txt");
        PrintStream pout = new PrintStream(out);
        List<String[]> entries = new ArrayList<String[]>();
        Scanner sc = new Scanner(new File("/Users/evanlivingston/dists/0.txt"));
        while (sc.hasNext()) {
            entries.add(new String[] { sc.next(), sc.next()});
        }
        String[][] table = entries.toArray(new String[0][]);

        Arrays.sort(table, new Comparator<String[]>() {
            @Override
            public int compare(String[] s1, String[] s2) {
                String t1 = s1[0];
                String t2 = s2[0];
                return t1.compareTo(t2);               
            }      
        });
        pout.print(java.util.Arrays.deepToString(table));
        pout.close();
    }
}

EDIT : 编辑
Here is my updated code. 这是我更新的代码。 It won't compile. 它不会编译。

import java.io.*;
import java.util.*;

public class Sort {
    public static void main(String[] args) throws FileNotFoundException {
        FileOutputStream out = new FileOutputStream("/Users/evanlivingston/2d.txt");
        PrintStream pout = new PrintStream(out);
        List<Coords> coords = new ArrayList<Coords>();
        {
            Scanner sc = new Scanner(new File("/Users/evanlivingston/dists/0.txt"));
            while(sc.hasNextLine()) {
                String[] numstrs = sc.nextLine().split("\\s+");
            }
            String[][] table = coords.toArray(new String[0][]);

            Arrays.sort(table, new Comparator<Double[]>() {
                @Override
                public int compare(Double[] s1, Double[] s2) {
                    double a = Double.parseDouble(s1);
                    double b = Double.parseDouble(s2);
                    compare(a, b);
                }
            });
            pout.print(java.util.Arrays.deepToString(table));
            pout.close();
        }
    }
}

Store doubles in the array NOT Strings. 将双打存储在数组NOT Strings中。

So convert the String to a double when you read it in from your file. 因此,当您从文件中读取字符串时,请将其转换为双精度型。 Or use the Scanner.nextDouble() method to do this for you. 或使用Scanner.nextDouble()方法为您完成此操作。

You don't want to be converting the Strings every time the Comparator is invoked. 您不想每次调用比较器时都转换字符串。

You're comparing String values, not Double values, so 2 comes after 1 and before 6. 您正在比较String值,而不是Double值,因此2在1之前和6之前。

To fix this, you should convert your values to actual Double objects with the wrapper method valueOf() ( documentation ). 要解决此问题,您应该使用包装方法valueOf()文档 )将值转换为实际的Double对象。

EDIT : 编辑
I went for the simpler fix above, but camickr's answer is better if you care at all about performance. 我选择了上面的简单修复程序,但是如果您完全关心性能,camickr的答案会更好。

Regarding your update not compiling, multiple things are wrong. 关于您的更新未编译,有很多错误。 Did you ever declare a second compare() method anywhere? 您是否曾经在任何地方声明过第二个compare()方法? There's nothing built in for that. 没有内置的东西。 Recursively calling the existing compare() won't help in your case. 递归调用现有的compare()对您的情况没有帮助。

On that note, you can't call the existing compare() ; 需要注意的是,您不能调用现有的compare() ; autoboxing won't convert primitive double s into arrays of Double objects. 自动装箱不会将原始double转换为Double对象的数组。 And there's no way to parse Double arrays into primitive double s. 而且没有办法将Double数组解析为原始double

Since you're trying to use primitive double s now, you could just use the plain old > and < operators to compare with instead of the more complex Comparator stuff. 由于您现在尝试使用原始double ,因此可以只使用普通的><运算符进行比较,而不必使用更复杂的Comparator东西。

You're comparing strings, not numeric values. 您正在比较字符串,而不是数字值。 1 is lexically lower than 2, and 2 is lexically lower than three. 1在词法上低于2,而2在词法上低于3。 So from a string perspective, 234 is less than 3. You have to convert your doubles from strings in order to compare them properly. 因此,从字符串的角度来看,234小于3。您必须将stringsdoubles转换为正确的比较。 In Java you do this via: 在Java中,您可以通过以下方式进行操作:

double aDouble = Double.parseDouble(aString);

so your final expression should really be 所以你的最终表达应该是

double a = Double.parseDouble(firstString);
double b = Double.parseDouble(secondString);
compare(a,b);

Have your comparator convert the strings it is input into doubles and do a numeric comparison rather than a string compare. 让您的比较器将输入的字符串转换为双精度并执行数字比较,而不是字符串比较。

That's the advantage of the Comparator concept. 这就是Comparator概念的优势。 It can do anything with the inputs. 它可以对输入执行任何操作。 So if you need to sort Strings as if they were numbers, write a Comparator that'll do just that. 因此,如果您需要像对待数字一样对Strings进行排序,请编写一个Comparator来完成。

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

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