Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Can anyone tell me why I should or should not return an object as opposed to the generic element I'm working with? Both seem to have upsides and downsides... what's the best practice?</p> </blockquote> <p>It depends. In a case like this you'd want to generic type - otherwise what's the point of defining generic type for the class? </p> <blockquote> <p>I know vaguely that returning an Object can cause some casting issues later on but I've not yet run into them... does anyone have a specific example of how this can be dangerous?</p> </blockquote> <p>Sure! </p> <pre class="lang-or-tag-here prettyprint-override"><code>DansPriorityQueue&lt;String&gt; queue = new DansPriorityQueue&lt;String&gt;(); //add items Float f = (Float)queue.getObject(); //uh-oh! this compiles but will fail Float f = queue.getObject(); //generic type, fails during compile </code></pre> <blockquote> <p>In the JDK, I've noticed that many of the Collections methods return Object by default. Is this because Generics was introduced in a later version of Java or was this a conscious decision by Sun Systems?</p> </blockquote> <p>It's due to backward compatibility mostly, or for cases where you truly will use the collection to contain disparate values (a mishmash of say, JLabels, Strings and Icons for instance for rendering a JTable for instance).</p> <blockquote> <p>assertEquals("Expected different size", (Integer) 2, dpq.size());</p> </blockquote> <p>I don't think this should be a problem. dpq.size() should just return an int regardless off what is stored in the priority queue. It would not be a generic value.</p> <p>You can create something like </p> <pre class="lang-or-tag-here prettyprint-override"><code>DansPriorityQueue&lt;Double&gt; queue = new DansPriorityQueue&lt;Double&gt;(); for(double d = 0; d &lt; 10; d+=1.0) queue.add(d); </code></pre> <p>and that should cause no issues, right?</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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