我有基本的 Rectangle 類。我可以在沒有參考的情況下使用物件嗎?我試過了,但似乎只添加了最后一個。
public class Rectangle implements Comparable {
int a1;
int a2;
public Rectangle (int a1, int a2) {
this.a1= a1;
this.a2= a2;
}
TreeMap<Rectangle, String > rectangleStringTreeMap = new TreeMap<>();
rectangleStringTreeMap.put(new Rectangle(2,5),"This is first");
rectangleStringTreeMap.put(new Rectangle(3,7),"This is second");
rectangleStringTreeMap.put(new Rectangle(4,8),"This is third");
uj5u.com熱心網友回復:
如果您的類主要是作為一個透明的、不可變的資料載體,請將您的類定義為record。在記錄時,編譯器隱式創建的構造,干將,equals與hashCode和toString考慮每一個成員欄位。
讓你的類Comparable使用泛型而不是原始型別來實作。
Comparator用兩個子句定義一個,做比較作業。
像這個未經測驗的代碼。
public record Rectangle ( int a1 , int a2 ) implements Comparable < Rectangle >
{
static private Comparator < Rectangle > comparator =
Comparator
.comparingInt( Rectangle :: a1 )
.thenComparingInt( Rectangle :: a2 ) ;
@Override
public int compareTo( Rectangle other )
{
return Rectangle.comparator.compare( this , other ) ;
}
}
繼續你的地圖。但是將您的地圖宣告為更通用的介面NavigableMap而不是具體的類TreeMap。
NavigableMap < Rectangle, String > rectangleStringNavMap = new TreeMap<>();
rectangleStringNavMap.put( new Rectangle(2,5), "This is first" );
rectangleStringNavMap.put( new Rectangle(3,7), "This is second" );
rectangleStringNavMap.put( new Rectangle(4,8), "This is third" );
如果跨執行緒使用映射,請使用ConcurrentNavigableMap介面和ConcurrentSkipListMap類。
uj5u.com熱心網友回復:
我在使用比較器而不是使用 Comparable 介面時解決了這個問題。
public class Rectangle{
int a1;
int a2;
public Rectangle (int a1, int a2) {
this.a1= a1;
this.a2= a2;
}
TreeMap<Rectangle, String > rectangleStringTreeMap = new TreeMap<>(new Comparator<Rectangle>() {
@Override
public int compare(Rectangle o1, Rectangle o2) {
if (o1.a1 > o2.a1 && o1.a2 > o2.a2) {
return 1;
} else if (o1.a1 < o2.a1 && o1.a2 < o2.a2) {
return -1;
} else return 0;
}
});
rectangleStringTreeMap.put(new Rectangle(2,5),"This is first");
rectangleStringTreeMap.put(new Rectangle(3,7),"This is second");
rectangleStringTreeMap.put(new Rectangle(4,8),"This is third");
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370493.html
上一篇:通過ID未連接的檔案
