I have a problem with an interface in Java.
The interface:
public interface Comparable<ContentType> {
public boolean isGreater ( ContentType pContent );
public boolean isEqual ( ContentType pContent );
public boolean isLess ( ContentType pContent );
}
The class "Point" implementing the interface:
public class Point implements Comparable<Point>{
private double x;
private double y;
public Point ( double pX, double pY ) {
x = pX;
y = pY;
}
public boolean isLess ( Point pContent ) {
if ( this.distance() < pContent.distance() ) {
return true;
} else {
return false;
}
}
public boolean isEqual ( Point pContent ) {
if ( this.distance() == pContent.distance() ) {
return true;
} else {
return false;
}
}
public boolean isGreater ( Point pContent ) {
if ( this.distance() > pContent.distance() ) {
return true;
} else {
return false;
}
}
public double distance() {
return Math.sqrt( x*x + y*y );
}
}
The class "Algorithms" has an insort-method for the interface Comparable and tests this insort-method:
public class Algorithms {
public static List<Comparable> insortComparable( Queue<Comparable> pQueue ) {
List<Comparable> l = new List<Comparable>();
while ( !pQueue.isEmpty() ) {
if ( l.isEmpty() ) {
l.append(pQueue.front());
pQueue.dequeue();
} else {
l.toFirst();
while (l.hasAccess() && pQueue.front().isGreater(l.getContent())) {
l.next();
}
if ( l.hasAccess() ) {
l.insert(pQueue.front());
} else {
l.append(pQueue.front());
}
pQueue.dequeue();
}
}
return l;
}
public static Queue<Point> randomQueuePoint() {
Queue<Point> q = new Queue<Point>();
for ( int i = 0; i < 10; i++ ) {
q.enqueue( new Point( Math.random()*100, Math.random()) );
}
return q;
}
public void test() {
Queue<Point> q = randomQueuePoint();
List<Point> l = insortComparable(q);
}
}
In the test method I call the method insortComparable(q)
but the compiler underlines q and the compiler says:
incompatible types: Queue<Point> cannot be converted to Queue<Comparable>
Where is the problem?
Update:
I found my mistake and I wanted to give you an update, so people who have the same problem get some help.
One could say:
public static <T extends Comparable> List<T> insortComparable( Queue<T> pQueue ) {
List<T> l = new List<T>();
while ( !pQueue.isEmpty() ) {
if ( l.isEmpty() ) {
l.append(pQueue.front());
pQueue.dequeue();
} else {
l.toFirst();
while (l.hasAccess() && pQueue.front().isGreater(l.getContent())) {
l.next();
}
if ( l.hasAccess() ) {
l.insert(pQueue.front());
} else {
l.append(pQueue.front());
}
pQueue.dequeue();
}
}
return l;
}