I'm trying to implement a custom sorted binary tree in java, and I've had some problems with comparisons. I'm trying to implement a generic tree, so I would like to do something like:
public boolean contains(int i){
if(i == currentNode.value)
return true;
else if (i > currentNode.value)
// Go right
else if (i < currentNode.value)
// Go left
...
}
But I'm using objects (and I'm assuming they are objects that can be compared), so I wanted to do something like:
public boolean contains(Object o){
if(o == currentNode.value) // value is of Object class
return true;
else if (o > currentNode.value) // Problem
// Go right
...
}
So my problem right now is that it's not possible to use the operators > and < with objects, and so far I've been unable to think of another way to go about this.
Objects are not in inherently comparable, is an apple greater then an orange? Objects that are comparable implement the interface Comparable. So the simple answer is to replace every instance of Object in your binary tree with Comparable and have
int comparison = o.compareTo(currentNode.Value)
if(comparison ==0){
...
} else if (comparison > 0) {
...
} else {
// comparison < 0
...
}
You probably want to learn about java generics, which make your code much more type safe.
You would start like this
public class BinaryTree<T extends Comparable> {
public boolean contains(T target) {
....
}
...
}
Then you could use it like
BinaryTree<Integer> tree = ...
tree.add(1);
tree.add(2);
tree.add("three"); // <-- Syntax error, compiler would fail.
...
Integer first = tree.getFirst();
Integer last = tree.getLast();
Objects that implement Comparable in java will have an method called compareTo that returns a integer. You just need to do your > and < tests on that, that is:
int res = comparable.compareTo(other);
if(res == 0){
return true;
} else if(res > 0){
//go right
...
} else {
//go left
...
}
If you are using any Object, then override the equals() method, for equality check. If you want to compare them, then implement the Comparable interface, or create a Comparator for them.
This answer won't explain in detail, how to use them, please read the docs (They are pretty detailed, and give you a good start, on the usage), or search for example usages, the internet is full of them.
This is exactly what java comparable and generics are for!
Your objects should implement the: "int compareTo(Object obj)" method. If you were creating a binary search tree your contain method would look something like:
public class MyTree<T extends Comparable<T>>{
...
public boolean contains(TreeNode<T> node, T target)(
if(node == null) return false;
if(node.data.equals(target)){
return true;
}
if(node.data.compareTo(target) > 0){//node is greater than target go left
return contains(node.left, target);
}else{
return contains(node.right, target)//node is less than target go right
}
}
}
Related
I have a class Product, which three variables:
class Product implements Comparable<Product>{
private Type type; // Type is an enum
Set<Attribute> attributes; // Attribute is a regular class
ProductName name; // ProductName is another enum
}
I used Eclipse to automatically generate the equal() and hashcode() methods:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
if (type != other.type)
return false;
return true;
}
Now in my application I need to sort a Set of Product, so I need to implement the Comparable interface and compareTo method:
#Override
public int compareTo(Product other){
int diff = type.hashCode() - other.getType().hashCode();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
}
diff = attributes.hashCode() - other.getAttributes().hashCode();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
}
return 0;
}
Does this implementation make sense? What about if I just want to sort the product based on the String values of "type" and "attributes" values. So how to implement this?
Edit:
The reason I want to sort a Set of is because I have Junit test which asserts on the string values of a HashSet. My goal is to maintain the same order of output as I sort the set. otherwise, even if the Set's values are the same, the assertion will fail due to random output of a set.
Edit2:
Through the discussion, it's clear that to assert the equality of String values of a HashSet isn't good in unit tests. For my situation I currently write a sort() function to sort the HashSet String values in natural ordering, so it can consistently output the same String value for my unit tests and that suffice for now. Thanks all.
Looks like from all the comments in here you dont need to use Comparator at all. Because:
1) You are using HashSet that does not work with Comparator. It is not ordered.
2) You just need to make sure that two HashSets containing Products are equal. It means they are same size and contain the same set of Products.
Since you already added hashCode and equals methods to Product all you need to do is call equals method on those HashSets.
HashSet<Product> set1 = ...
HashSet<Product> set2 = ...
assertTrue( set1.equals(set2) );
This implementation does not seem to be consistent. You have no control over how the hash codes look like. If you have obj1 < obj2 according to compareTo in the first try, the next time you start your JVM it could be the other way around obj1 > obj2.
The only thing that you really know is that if diff == 0 then the objects are considered to be equal. However you can also just use the equals method for that check.
It is now up to you how you define when obj1 < obj2 or obj1 > obj2. Just make sure that it is consistent.
By the way, you know that the current implementation does not include ProductName name in the equals check? Dont know if that is intended thus the remark.
The question is, what do you know about that attributes? Maybe they implement Comparable (for example if they are Numbers), then you can order according to their compareTo method. If you totally know nothing about the objects, it will be hard to build up a consistent ordering.
If you just want them to be ordered consistently but the ordering itself does not play any role, you could just give them ids at creation time and sort by them. At this point you could indeed use the hashcodes if it does not matter that it can change between JVM calls, but only then.
I am trying to test a class for a test-assignment poker-game in which it is only important to determine the validity or value of particular hands.
My PokerHand object contains a TreeSet<Card>. I thought this would be an ideal data-structure since doubles are not allowed, and it automagically sorts it with red-black tree algorithm.
The problem however, is that it appears to have some side-effects that I am not yet aware of. I understand that doubles will not be added to a TreeSet, but in my tests I make sure not to. Instead I noticed that it will not add new Card objects to the TreeSet as soon as the number fields are equal, but not the type.
This is the equals method for a Card
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Card other = (Card) obj;
return this.type == other.type && this.number == other.number;
}
This is the test, adding various cards...
#Test
public void testOnePair() {
hand.addCard(new Card(3, Card.CARD_TYPE.SPADES));
hand.addCard(new Card(8, Card.CARD_TYPE.CLUBS));
hand.addCard(new Card(10, Card.CARD_TYPE.HEARTS));
hand.addCard(new Card(14, Card.CARD_TYPE.SPADES));
hand.addCard(new Card(14, Card.CARD_TYPE.CLUBS));
assertEquals("One Pair", this.hand.getValue());
}
What appears to be happening is that the last Card is not added, so the size of the TreeSet effectively remains 4, even though the cards are clearly distinct. It does not even consult the equals method.
It does however reach the compareTo method.
#Override
public int compareTo(Object t) {
if (t.getClass().equals(this.getClass())) {
Card otherCard = (Card)t;
if (otherCard.equals(this)) {
return 0;
}
return this.number - otherCard.number;
}
else {
throw new ClassCastException("Cannot convert " + t.getClass().toString() + " to Card");
}
}
It has been a while since I've gotten back into Java 8 and maybe I'm just clearly overseeing something. I hope somebody can help me forward with this.
I've always been reluctant to ask questions here. Solved this as soon as I submitted it... Wanted to share this with you. TreeSet only cares about the compareTo method. So I changed it to be the following.
#Override
public int compareTo(Object t) {
if (t.getClass().equals(this.getClass())) {
Card otherCard = (Card)t;
if (this.number == otherCard.number) return this.type.compareTo(otherCard.type);
return this.number - otherCard.number;
}
else {
throw new ClassCastException("Cannot convert " + t.getClass().toString() + " to Card");
}
}
This solved it, because now the comparable contract is "aware" of the type properties.
I'm new to Java and still trying to wrap my head around recursion.The function below returns true at the very first intersection between the two sorted lists list x and list y.
public static boolean checkIntersection(List<Integer> x, List<Integer> y) {
int i = 0;
int j = 0;
while (i < x.size() && j < y.size()) {
if (x.get(i).equals(y.get(j))) {
return true;
} else if (x.get(i) < y.get(j)) {
i++;
} else {
j++;
}
}
return false;
}
Now I've been trying to implement it using recursion instead, and I know that there should be a base case which is an empty list in this case and then try to reduce the list by excluding one element at a time and feed it back to the same recursive function, but I can't work out how to check for intersection as I pass the rest of the list over and over.
public static boolean recursiveChecking(List<Integer> x,List<Integer> y) {
if(x.size() == 0){
return false;
}
else {
return recursiveChecking(x.subList(1, x.size()-1), y);
}
}
Any help would be highly appreciated. Thank you.
General approach to making something recursive is to think of two things:
When can I produce an answer trivially? - An answer to this question lets you code the base case. In your situation, you can produce the answer trivially when at least one of two lists is empty (the result would be false) or the initial elements of both non-empty lists are the same (the result would be true)
How do I reduce the problem when the answer is non-trivial? - An answer to this question lets you decide how to make your recursive call. In your case you could, for example, remove the initial element of one of the lists before making the recursive call*, or pass ListIterator<Integer> in place of List<Integer> for a non-destructive solution.
*Of course in this case you need to take care of either adding your numbers back after the call, or make a copy of two lists before starting the recursive chain.
As the lists are ordered, your recursion should remove the first element of the list with the smaller first value. Then you have to return true, if both lists start with the same number and false if any of the lists is empty. Otherwise you keep removing elements. This would look something like this (This code is untested):
public static boolean recursiveChecking(List<Integer> x,List<Integer> y) {
if(x.size() == 0 || y.size() == 0){
return false;
} else if (x.get(0).equals(y.get(0))) {
return true;
} else {
if (x.get(0) < y.get(0)) {
return recursiveChecking(x.subList(1, x.size()-1), y);
} else {
return recursiveChecking(x, y.subList(1, y.size()-1));
}
}
}
class Obj{
int x;
int y;
Date z;
public int compareTo(Obj other) {
if(this.z.getTime() > other.getZ().getTime())
return 1;
else if(this.z.getTime() < other.getZ().getTime())
return -1;
else
return 0;
}
boolean equals(Obj other) {
if(x== other.x && y == other.y)
return true;
else
return false;
}
}
Now I have a list<Obj> and I have to remove duplicate and only pick the latest one (latest z) when there are multiple object with same id.
sortedSet = new TreeSet(objList);
reversedSortedList = new ArrayList(sortedSet); //This will not be needed if we reverse the comparator logic. However it is not good.
uniqueSet = new HashSet(reverseSortedList);
return uniqueSet;
Is this a good way of doing things. Or there is a cleaner and better way of doing things. Also the number of element in the list for me lies between 1000-10000
Thanks
You can write a separate Comparator to compare your object which will have the capability to sort in reverse(just opposite logic what you have implemented) instead of implementing compareTo method in our object(while I can see that your class doesn't implement Comparable interface).
In that way you will be able to directly get the reversely sorted Set and you can change the logic easily anytime you want or can use many different comparators at the different places.
For 1000-10000 using TreeSet is a good option with Compartors.
You comparator could be optimized to:
public int compareTo(Obj other) {
return (int)(this.z.getTime() - other.getZ().getTime());
}
So I've been struggling with a problem for a while now, figured I might as well ask for help here.
I'm adding Ticket objects to a TreeSet, Ticket implements Comparable and has overridden equals(), hashCode() and CompareTo() methods. I need to check if an object is already in the TreeSet using contains(). Now after adding 2 elements to the set it all checks out fine, yet after adding a third it gets messed up.
running this little piece of code after adding a third element to the TreeSet, Ticket temp2 is the object I'm checking for(verkoopLijst).
Ticket temp2 = new Ticket(boeking, TicketType.STANDAARD, 1,1);
System.out.println(verkoop.getVerkoopLijst().first().hashCode());
System.out.println(temp2.hashCode());
System.out.println(verkoop.getVerkoopLijst().first().equals(temp2));
System.out.println(verkoop.getVerkoopLijst().first().compareTo(temp2));
System.out.println(verkoop.getVerkoopLijst().contains(temp2));
returns this:
22106622
22106622
true
0
false
Now my question would be how this is even possible?
Edit:
public class Ticket implements Comparable{
private int rijNr, stoelNr;
private TicketType ticketType;
private Boeking boeking;
public Ticket(Boeking boeking, TicketType ticketType, int rijNr, int stoelNr){
//setters
}
#Override
public int hashCode(){
return boeking.getBoekingDatum().hashCode();
}
#Override
#SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
public boolean equals(Object o){
Ticket t = (Ticket) o;
if(this.boeking.equals(t.getBoeking())
&&
this.rijNr == t.getRijNr() && this.stoelNr == t.getStoelNr()
&&
this.ticketType.equals(t.getTicketType()))
{
return true;
}
else return false;
}
/*I adjusted compareTo this way because I need to make sure there are no duplicate Tickets in my treeset. Treeset seems to call CompareTo() to check for equality before adding an object to the set, instead of equals().
*/
#Override
public int compareTo(Object o) {
int output = 0;
if (boeking.compareTo(((Ticket) o).getBoeking())==0)
{
if(this.equals(o))
{
return output;
}
else return 1;
}
else output = boeking.compareTo(((Ticket) o).getBoeking());
return output;
}
//Getters & Setters
On compareTo contract
The problem is in your compareTo. Here's an excerpt from the documentation:
Implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.
Your original code is reproduced here for reference:
// original compareTo implementation with bug marked
#Override
public int compareTo(Object o) {
int output = 0;
if (boeking.compareTo(((Ticket) o).getBoeking())==0)
{
if(this.equals(o))
{
return output;
}
else return 1; // BUG!!!! See explanation below!
}
else output = boeking.compareTo(((Ticket) o).getBoeking());
return output;
}
Why is the return 1; a bug? Consider the following scenario:
Given Ticket t1, t2
Given t1.boeking.compareTo(t2.boeking) == 0
Given t1.equals(t2) return false
Now we have both of the following:
t1.compareTo(t2) returns 1
t2.compareTo(t1) returns 1
That last consequence is a violation of the compareTo contract.
Fixing the problem
First and foremost, you should have taken advantage of the fact that Comparable<T> is a parameterizable generic type. That is, instead of:
// original declaration; uses raw type!
public class Ticket implements Comparable
it'd be much more appropriate to instead declare something like this:
// improved declaration! uses parameterized Comparable<T>
public class Ticket implements Comparable<Ticket>
Now we can write our compareTo(Ticket) (no longer compareTo(Object)). There are many ways to rewrite this, but here's a rather simplistic one that works:
#Override public int compareTo(Ticket t) {
int v;
v = this.boeking.compareTo(t.boeking);
if (v != 0) return v;
v = compareInt(this.rijNr, t.rijNr);
if (v != 0) return v;
v = compareInt(this.stoelNr, t.stoelNr);
if (v != 0) return v;
v = compareInt(this.ticketType, t.ticketType);
if (v != 0) return v;
return 0;
}
private static int compareInt(int i1, int i2) {
if (i1 < i2) {
return -1;
} else if (i1 > i2) {
return +1;
} else {
return 0;
}
}
Now we can also define equals(Object) in terms of compareTo(Ticket) instead of the other way around:
#Override public boolean equals(Object o) {
return (o instanceof Ticket) && (this.compareTo((Ticket) o) == 0);
}
Note the structure of the compareTo: it has multiple return statements, but in fact, the flow of logic is quite readable. Note also how the priority of the sorting criteria is explicit, and easily reorderable should you have different priorities in mind.
Related questions
What is a raw type and why shouldn't we use it?
How to sort an array or ArrayList ASC first by x and then by y?
Should a function have only one return statement?
This could happen if your compareTo method isn't consistent. I.e. if a.compareTo(b) > 0, then b.compareTo(a) must be < 0. And if a.compareTo(b) > 0 and b.compareTo(c) > 0, then a.compareTo(c) must be > 0. If those aren't true, TreeSet can get all confused.
Firstly, if you are using a TreeSet, the actual behavior of your hashCode methods won't affect the results. TreeSet does not rely on hashing.
Really we need to see more code; e.g. the actual implementations of the equals and compareTo methods, and the code that instantiates the TreeSet.
However, if I was to guess, it would be that you have overloaded the equals method by declaring it with the signature boolean equals(Ticket other). That would lead to the behavior that you are seeing. To get the required behavior, you must override the method; e.g.
#Override
public boolean equals(Object other) { ...
(It is a good idea to put in the #Override annotation to make it clear that the method overrides a method in the superclass, or implements a method in an interface. If your method isn't actually an override, then you'll get a compilation error ... which would be a good thing.)
EDIT
Based on the code that you have added to the question, the problem is not overload vs override. (As I said, I was only guessing ...)
It is most likely that the compareTo and equals are incorrect. It is still not entirely clear exactly where the bug is because the semantics of both methods depends on the compareTo and equals methods of the Boeking class.
The first if statement of the Ticket.compareTo looks highly suspicious. It looks like the return 1; could cause t1.compareTo(t2) and t2.compareTo(t1) to both return 1 for some tickets t1 and t2 ... and that would definitely be wrong.