Вот как я могу это сделать:
TypedProperty.java
/**
* A TypedProperty class - more than String.
* @link /9123847/kak-obyavit-java-sopostavimym-v-etoi-situatsii
*/
public class TypedProperty<T extends Comparable<T>> implements Comparable<TypedProperty<T>> {
private final T value;
private final Class<T> type;
public TypedProperty(T value, Class<T> clazz) {
this.value = value;
this.type = clazz;
}
public T getValue() {
return value;
}
public Class<T> getType() {
return type;
}
@Override
public int compareTo(TypedProperty<T> other) {
return this.value.compareTo(other.value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypedProperty<?> that = (TypedProperty<?>) o;
if (!getValue().equals(that.getValue())) return false;
return getType().equals(that.getType());
}
@Override
public int hashCode() {
int result = getValue().hashCode();
result = 31 * result + getType().hashCode();
return result;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("TypedProperty{");
sb.append("value=").append(value);
sb.append(", type=").append(type);
sb.append('}');
return sb.toString();
}
}
Тест JUnit, чтобы доказать, что он работает:
import org.junit.Assert;
import org.junit.Test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* @link /9123847/kak-obyavit-java-sopostavimym-v-etoi-situatsii
*/
public class TypedPropertyTest {
@Test
public void testConstructor_DateTypedProperty() throws ParseException {
// setup
String [] testDates = { "2019-06-07", "2018-03-17", "2017-01-01" };
List<String> expected = Arrays.asList(testDates);
Collections.sort(expected);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<TypedProperty<Date>> typedProperties = new ArrayList<>();
for (String testDate : testDates) {
typedProperties.add(new TypedProperty<>(format.parse(testDate), Date.class));
}
// test
Collections.sort(typedProperties);
// assert
for (int i = 0; i < typedProperties.size(); ++i) {
Assert.assertEquals(format.parse(expected.get(i)), typedProperties.get(i).getValue());
}
}
}