简体   繁体   中英

Using the Collections.max for a Period (java)

So I have a List<Period> periods = new Arraylist<>(); which stores my dates which it gets from the database. (Period being my own class, forgot to mention)

The List kinda looks like this: 2012-02-03, 2012-02-04, 2012-03-05, 2012-03-07, 2012-03-08, 2012-03-09, 2012-03-10 and I need to find the biggest period out of the list. So the outcome would have to be period: 2012-03-07 to 2012-03-10 .

Now I thought I would use the collection method like this: Period biggestperiod = Collections.max(periods); except it doesnt work and I get the next error: "max(java.util.Collection) in Collections cannot be applied to (java.util.List) reason; no instance of type variables T exist so that Period conforms to Comparable .

Im a complete noob when it comes to programming so could someone point me in the right direction?

I'm guessing Period is one of your own classes, if it's Java's Period , you have to use Collections.max with the additional Comparator you cannot use the Collections.max function without it. To use the Collections.max method without an additional Comparator , Period has to implement Comparable - java.time.Period doesn't.

See https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max(java.util.Collection) for reference and https://docs.oracle.com/javase/8/docs/api/java/time/Period.html for the Period class.

I just wrote a simple example of how this works:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Number implements Comparable
{
public int number;

public Number(int number)
{
    this.number = number;
}

@Override
public int compareTo(Object arg0)
{
    if (number > ((Number) arg0).number) {
        return 1;
    }
    if (number == ((Number) arg0).number) {
        return 0;
    }
    if (number < ((Number) arg0).number) {
        return -1;
    }
    return -2;

}

public static void main(String[] args)
{
    Number one = new Number(1);
    Number three = new Number(3);
    Number two = new Number(2);

    List<Number> numberList = new ArrayList<>();
    numberList.add(one);
    numberList.add(three);
    numberList.add(two);

    System.err.println(Collections.max(numberList).number);
}
}

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