Here are some notes on implementations using Generics.
If you declare something that specifies generics normally, it tends to be redundant, so if you want to generate such an object many times, I think it is better to create a generation function in the Util class.
Implementation example
//A function that returns a List corresponding to the class
<T> List<T> generateList(Class<T> clazz) {
return new ArrayList<>();
}
//A function that returns a BeanPropertyRowMapper that corresponds to the class
<T> BeanPropertyRowMapper<T> getBeanPropertyRowMapper(Class<T> clazz) {
return new BeanPropertyRowMapper<>(clazz);
}
Usage example
//Redundant when written like this
new BeanPropertyRowMapper<Something>(Something.class);
//It is easier to read if you write like this
Util.getBeanPropertyRowMapper(Something.class);
In the case of "use a type that takes generics, but the type of the contents does not matter", simply omitting the type will give a warning.
Example of warning
//Duplicate check using hash set
boolean checkForDuplicate(List list) {
return list.size() == new HashSet(list).size();
}
In such cases, you can write <?>
And the diamond operator to avoid warnings.
Implementation example
//Duplicate check using hash set
boolean checkForDuplicate(List<?> list) {
return list.size() == new HashSet<>(list).size();
}
You can write it by specifying it with <T>
, but it will be a little redundant.
Redundant implementation example
//Duplicate check using hash set
<T> boolean checkForDuplicate(List<T> list) {
return list.size() == new HashSet<>(list).size();
}
Even when performing Stream
processing with List
as an argument, compilation may not pass unless <?>
Is written.
Example that compilation does not pass
BeanPropertySqlParameterSource[] makeParamArray(List entities) {
return entities.stream()
.map(BeanPropertySqlParameterSource::new)
.toArray(BeanPropertySqlParameterSource[]::new);
}
Example of compiling
BeanPropertySqlParameterSource[] makeParamArray(List<?> entities) {
return entities.stream()
.map(BeanPropertySqlParameterSource::new)
.toArray(BeanPropertySqlParameterSource[]::new);
}
Recommended Posts