How do I sort Java objects?

Asked 2 years ago, Updated 2 years ago, 102 views

Please enter the code here //

 .
private Product[] products = null;

private void searchFromDate(Product[] plist) {      

    }

After making it like this, I would like to arrange the productId (product number) in the class called Product in ascending order. I tried all the Collections and sort functions, but I got an error and it was impossible. As you can see from the functional factor, it's a separate object type called Product[], not int or String. For example, if you try to sort with Collections.sort(plist);, the method sort(List) in the type Collections is not applicable for the arguments (Product[]) appears. The same goes for "sort." I want to know how to sort the productId of this object in ascending order.

sorting java

2022-09-20 21:45

1 Answers

This is because you have not defined the sorting criteria for the class Product.

class Product implements Comparable<Product> {

    @Override
    public int compareTo(Product p) {
        return getProductId() - p.getProductId();
    }
}

When you declare Product, you can define CompareTo in this wayYo

If you still don't know, search java comparable


2022-09-20 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.