I have basic Rectangle class. Can I use the object without reference? I'tried but it seems like only adding the last one.
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");
CodePudding user response:
If your class is primarily meant to be a transparent immutable carrier of data, define your class as a record. In a record, the compiler implicitly creates the constructor, getters, equals
& hashCode
, and toString
by considering each and every member field.
Make your class implement Comparable
using generics rather than as a raw type.
Define a Comparator
with two clauses, to do the comparing work.
Something like this untested code.
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 ) ;
}
}
Proceed with your map. But declare your map as the more general interface NavigableMap
rather than the concrete class 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" );
If working with the map across threads, use ConcurrentNavigableMap
interface, and ConcurrentSkipListMap
class.
CodePudding user response:
I solved the problem while using comparator instead of using Comparable interface.
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");