Reputation: 4239
I am new to Java. Basically, I created my own generic Heap data structure that will accept any type of objects. And the Heap data structure contains a method that compares 2 objects like this: heap[ parent(i)] <= heap[i]
. Obviously, this will cause an error because I cannot use <=
to compare two objects.
Question 1: I need to write a method to replace <=
such that if I pass in any two objects it will automatically do the equivalent of the <=
comparison . But I do not know how to do so.
class Heap<E>{
E[] heap;
// constructor
public Heap(E[] heap){
this.heap = heap;
}
public int parent(int i){
return (int) Math.floor(i/2.0);
}
...
// This is where the problem occurs
public boolean minHeapProperty(){
for(int i = 0; i < heap.length; i++){
// <= operator need to be replaced by a method can be used for comparison by all objects
if( !( heap[ parent(i) ] <= heap[i] )){
return false;
}
}
return true;
}
........
}
Question 2: I have another object class Vertex
and I am trying to write a method to compare 2 Vertex
objects by an instance variable node
. But I kept failing. Note that I will be creating a heap of Vertex
objects later on. So, I really only need a unique comparison method that can be used in both the Heap
generic class and the Vertex
class. This is why two questions are related and I do not want to post two separate questions on this website.
Vertex{
public int node;
public Vertex(int node){
this.node = node;
}
// compare two vertex objects (I do not know how to write this in the right way)
public boolean compareTwoVertexObjects(Vertex v2){
// need an answer here.
return (node <= v2.node);
}
}
Upvotes: 2
Views: 1204
Reputation: 201429
I suggest you modify the type of E
to specify that it must be Comparable
like
class Heap<E extends Comparable<E>>
then you can compare two instances a
and b
like
E a;
E b;
// ...
int c = a.compareTo(b);
if (c < 0) {
// a < b
} else if (c > 0) {
// a > b
} else {
// a == b
}
Then you might modify Vertex
to also be Comparable
with something like
class Vertex implements Comparable<Vertex> {
public int node;
public Vertex(int node) {
this.node = node;
}
@Override
public int compareTo(Vertex o) {
return Integer.valueOf(node).compareTo(o.node);
}
}
Upvotes: 3