简体   繁体   中英

Sorting an ArrayList object populated with custom objects with two data fields each

stuck on a problem with sorting ArrayLists. I'm sure the answer is really easy and something I just keep overlooking, but I've been working on this for the past many hours straight and just need someone else's eyes.

It's a lab project that required us to make 3 custom classes; Applications.java, Rectangle.java, and RectangleList.java and I have to sort an ArratList that contains Rectangle objects with length and width data fields.

The order is (W1, L1) > (W2, L2) if and only if [(W1 > W2) or (W1 = W2 and L1 > L2)

I'm not sure what bits of code would be necessary to look at for help, but I know I'm supposed to use for loops and no outside pre-made methods for sorting. I'm supposed to run a for loop through each index and compare that index to each other index and then switch values. My current bit of code either doesn't do anything (no sorting happens) or it throws up duplicates. Just lots of stuff going on and I've erased everything and started over many times. Not sure where to go from here, and I no longer know how to think of the problem.

Thanks, just let me know what you need to see and I'll try posting it.

Edit note: We aren't allowed to use comparator or comparable or any other compare method I don't know about yet.

///////////////////////////////////////////////////////////////////////////// I figured it out!

for(int index = 0; index < (list.boxes.size()-1); index++){
    minIndex = index;

    for(int index2 = index+1; index2 < list.boxes.size(); index2++){
        if((list.boxes.get(minIndex).getLength() > list.boxes.get(index2).getLength()) || (list.boxes.get(minIndex).getLength() == list.boxes.get(index2).getLength() && list.boxes.get(minIndex).getWidth() > list.boxes.get(index2).getWidth())){
            minIndex = index2;
        }
    }
    list.boxes.set(index, list.boxes.set(minIndex, list.boxes.get(index)));
}

I think the comparator could help you :

Collections.sort(rectList, new Comparator<Rectangle>() {
    @Override
    public int compare(Rectangle rect1, Rectangle rect2) {
        if(rect1.width > rect2.width)
            return -1;
        else if(rect1.width == rect2.width && rect1.length > rect2.length)
            return -1;
        else if(rect1.width == rect2.width && rect1.length == rect2.length)
            return 0;
        else
            return 1;
    }
});

If you are using Java8 then Lambda expression can be used to make the code smaller.

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