简体   繁体   English

Java-如何排序2D数组?

[英]Java - How do i sort 2D array?

I got a question about sorting an array. 我对排序数组有疑问。

i got an array like this: 我有一个像这样的数组:

long[][] allDate = new long[lenght][2];

and the valus are: allDate[][0] represend date in miliseconds and allDate[][1] represend value in this case its price of date from before for example 值是: allDate[][0]以毫秒为单位表示日期,而allDate[][1]这种方式表示值,例如

allDate[0][0] = 142142141
allDate[0][1] = 90

allDate[][0] value of date is always in future from now and what i want to do is to sort this dates in ascending chronological logic. allDate[][0]值永远是现在以后的日期,我要做的是按照升序排列此日期。 but the problem is i want to keep their price so i could do add it to my Jfreechart line chart. 但是问题是我想保持价格,因此可以将其添加到我的Jfreechart折线图中。

in this loop 在这个循环中

    for (int i = 0; i < a7; i++) {
        int day = (int) (new Date().getTime() + allDate[i][0] / (1000 * 60 * 60 * 24));
        int month = (int) (new Date().getTime() + allDate[i][0] / (1000 * 60 * 60));
        int year = (int) (new Date().getTime() + allDate[i][0] / (1000 * 60));
        s1.add(new Day(day, month, year), (eWallet + allDate[i][1]));
    }

any ideas how to sort it ? 任何想法如何排序?

and the valus are: allDate[][0] represend date in miliseconds and allDate[][1] represend value in this case its price of date from before 值是:allDate [] [0]以毫秒为单位表示日期,而allDate [] [1]以这种方式表示值,此日期之前的价格

So the first thing I'd do is avoid storing those as a 2D array. 因此,我要做的第一件事就是避免将它们存储为2D数组。 Instead, store a 1D collection (whether that's an array or a list) of the pair of values: 而是存储一对值的一维集合(无论是数组还是列表):

PriceSnapshot[] prices = ...;

Where PriceSnapshot would consist of a timestamp (whether that's as a long , a Date , a Joda Time Instant etc or whatever) and a price. PriceSnapshot由时间戳(无论是longDate ,Joda的Instant时间等)或价格组成。

At that point, you can easily write a Comparer<PriceSnapshot> to compare by time, and sort using that. 那时,您可以轻松编写一个Comparer<PriceSnapshot>以按时间进行比较,并使用该排序进行排序。 Of course you could write a Comparer<long[]> instead, but that wouldn't be nearly as nice. 当然,您可以改写一个Comparer<long[]> ,但是效果不尽如人意。

(Also note that with your current loop, you're taking "the current time" 3 times, which means you could end up with different dates. Bad idea. Take a single snapshot of "now" and then use that repeatedly.) (还要注意,在当前循环中,您要花费“当前时间” 3次,这意味着您可能会以不同的日期结束。这是个糟糕的主意。请为“ now”拍摄一张快照,然后重复使用它。)

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

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