Reputation: 1
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?
Upvotes: 0
Views: 333
Reputation: 6742
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);
}
}
Upvotes: 1