Re: Novice to Generics Trying to Implement a Generic Priority Queue
markspace wrote:
KevinSimonson wrote:
public PriorityQueue ( int size)
{
if (0<= size)
{ @SupressWarnings( "unchecked")
queue = (Da[]) new Object[ size];
PriorityQueue.java:14:<identifier> expected
queue = (Da[]) new Object[ size];
Kevin, you really do a fine job of posting a question with a good example,
well presented.
Interesting. I thought I could put that annotaion on an assignment. I guess
not. Oh well.
Annotations are allowed only at declarations.
public PriorityQueue(int size) throws BadSizeException {
if (0 <= size) {
@SuppressWarnings("unchecked")
Da[] temp = (Da[]) new Object[ size ];
queue = temp;
nmbrEntries = 0;
} else {...
private static boolean inOrder ( Da left
, Da right)
{
return left.compareTo< ? super Da>( right)<= 0;
}
PriorityQueue.java:25: illegal start of expression
return left.compareTo< ? super Da>( right)<= 0;
This bit goes on the declaration, not the invocation ;-)
public class PriorityQueue<Da extends Comparable<? super Da>> {...
In the actual use, you don't need any angle-brackety stuff:
private static boolean inOrder( Da left, Da right)
{
return left.compareTo( right ) <= 0;
}
You do, however, have to guard against a possible 'NullPointerException'. The
method is 'private', so it's up to its callers not to screw that up. You
enforce that with an assertion:
private static boolean inOrder( Da left, Da right)
{
assert left != null;
return left.compareTo( right ) <= 0;
}
If the method were 'public' you'd need to add an explicit guard against the
'NullPointerException':
public static boolean inOrder( Da left, Da right)
{
if ( left == null )
{
return true;
}
assert left != null;
return left.compareTo( right ) <= 0;
}
The assertion is rather trivial here, so you could simply:
public static boolean inOrder( Da left, Da right)
{
return left == null || left.compareTo( right ) <= 0;
}
Don't forget your Javadocs!
--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg