您好我有一个国家/地区类,其中包含countryLanguage集。 我想为每个国家排序语言。 我正在创建视图页面。国家和他的相应语言。 县是好的,但其语言不按排序顺序排列。 我很困惑在哪个类我使用隔离器和如何。
public class Country implements Serializable{
private Set<CountryLanguage> countryLanguage = new HashSet<CountryLanguage>(0);
//...
}
public class CountryLanguage {
private CountryLanguageID countryLangPK = new CountryLanguageID();
//...
}
复合id类
public class CountryLanguageID implements Serializable,Comparable<CountryLanguageID>{
private Country country;
private Language language;
@ManyToOne(fetch=FetchType.LAZY)
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
@ManyToOne(fetch=FetchType.LAZY)
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CountryLanguageID that = (CountryLanguageID) o;
if (country != null ? !country.equals(that.country) : that.country != null){
return false;
}
if (language != null ? !language.equals(that.language) : that.language != null){
return false;
}
return true;
}
public int hashCode() {
int result;
result = (country != null ? country.hashCode() : 0);
result = 31 * result + (language != null ? language.hashCode() : 0);
return result;
}
@Override
public int compareTo(CountryLanguageID o) {
//return this.language.compareTo(o.language);
return this.getLanguage().getLanguageName().compareTo(o.getLanguage().getLanguageName());
}
}
答案 0 :(得分:2)
您可以使用TreeSet
代替HashSet
来保留countryLanguage
:
private Set<CountryLanguage> countryLanguage = new TreeSet<CountryLanguage>(0);
TreeSet
的元素使用其自然顺序排序,或者可以使用Comparator
进行排序,通常在TreeSet
创建时提供。
如果您想使用natural ordering
的{{1}},请CountryLanguage
实施CountryLanguage
:
Comparable
如果您想使用public class CountryLanguage implements Comparable<CountryLanguage>{
@Override
public int compareTo(CountryLanguage cl) {
// Comparison logic
}
...
}
订购Comparator
的元素,请定义比较器:
countryLanguage
并在创建private static final Comparator<CountryLanguage> COMP = new Comparator<CountryLanguage>() {
@Override
public int compare(CountryLanguage o1, CountryLanguage o2) {
// Compare o1 with o2
}
};
时使用它:
TreeSet
修改强>
private Set<CountryLanguage> countryLanguage = new TreeSet<CountryLanguage>(COMP);
类型为set
。因此,为了对CountryLanguage
的元素进行排序,您需要Set<CountryLanguage> countryLanguage
实现CountryLanguage
(但您已定义Comparable
来实现CountryLanguageID
):
在比较Comparable
的实例时,您可以使用CountryLanguage
属性进行比较:
CountryLanguageID