简体   繁体   中英

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][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. but the problem is i want to keep their price so i could do add it to my Jfreechart line chart.

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

So the first thing I'd do is avoid storing those as a 2D array. 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.

At that point, you can easily write a Comparer<PriceSnapshot> to compare by time, and sort using that. Of course you could write a Comparer<long[]> instead, but that wouldn't be nearly as nice.

(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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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