I assume that the actual question here is about how you should handle the multiple int values. You can simply do a lexicographic comparison:
public static int compareByTime(Second s0, Second s1)
{
First f0 = s0.object;
First f1 = s1.object;
if (f0.month > f1.month) return 1;
if (f0.month < f1.month) return -1;
if (f0.day > f1.day) return 1;
if (f0.day < f1.day) return -1;
if (f0.hour > f1.hour) return 1;
if (f0.hour < f1.hour) return -1;
if (f0.minute > f1.minute) return 1;
if (f0.minute < f1.minute) return -1;
return 0;
}
In general, I'd recommend to not let a class implement Comparable
. You should do this only if the class has a natural ordering. And for your Second
class, this is certainly not the case. Using a Comparator
is much more flexible in most cases. However, this method can be used either for implementing Comparable
or for implementing a Comparator
.
EDIT: Elaborating it a little in response to the comment:
This method is intended for the general comparison of two Second
objects. You can either use it when you let your Second
class implement the Comparable
interface:
Second implements Serializable, Comparable<Second>
{
First object;
int temperature;
@Override
public int compareTo(Second other)
{
return compareByTime(this, other); // The method from above
}
}
Or you can use it when you create a Comparator
for Second
objects:
class SecondComparator implements Comparator<Second>
{
@Override
public int compare(Second s0, Second s1)
{
return compareByTime(s0, s1); // The method from above
}
}
In both cases, you can insert new objects into a collection like a TreeSet<Second>
, which is always sorted. Alternatively, if you used a List<Second>
, you could, for example, do a binary search for the index of where to insert the object. (Or simply add the new object to the list, and sort the list afterwards, but this would be rather inefficient)