Note that there are some explanatory texts on larger screens.

plurals
  1. POneed for casting to a generic type in java
    primarykey
    data
    text
    <p>while implementing a priority queue using a linkedlist(actually an inner class <code>Node</code>),I coded the <code>insert()</code> and <code>max()</code> methods as below.It uses the lazy approach of keeping the items unordered and then seaching through them for the maximum element only when a <code>max()</code> or <code>deleteMax()</code> call occurs.</p> <pre><code>public class LinkedListMaxPQ&lt;Item extends Comparable&lt;Item&gt;&gt;{ private int N; private Node head; public void insert(Item item) { Node old = head; head = new Node(); head.item = item; head.next = old; N++; } public Item max() { Item maxitem = (Item) this.head.item; for(Node t=head.next;t!=null;t=t.next){ if(gt(t.item,maxitem)){ maxitem = (Item) t.item; } } return maxitem; } private boolean gt(Comparable x,Comparable y){ return x.compareTo(y) &gt; 0; } private class Node&lt;Item extends Comparable&lt;Item&gt;&gt;{ Item item; Node next; } } </code></pre> <p>I am wondering why I need the cast in <code>Item maxitem = (Item) this.head.item</code> ? Since the class uses a generic type <code>Item which extends Comparable</code> and the inner class also uses Item extends Comparable ,one would think that such a cast is unnecessary.</p> <p>If I omit the cast </p> <pre><code>Item maxitem = this.head.item; </code></pre> <p>compiler will complain that there is a type mismatch</p> <blockquote> <p>Type mismatch: cannot convert from Comparable to Item</p> </blockquote> <p>Can someone explain why this occurs?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload