Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't autoboxing work in this case with generics?
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/517751/java-array-of-primitive-data-types-does-not-autobox">Java: Array of primitive data types does not autobox</a> </p> </blockquote> <p>I've been doing some Java lately (mostly as a recap on what I did at university as my current job doesn't involve any Java at all) and one thing that never got introduced to us properly is Generics.</p> <p>I've been doing the Generics tutorial on the Oracle Java website and I've been stumped by the following example that I modified a bit:</p> <pre><code>public static &lt;Integer extends Comparable&lt;Integer&gt;&gt; int countGreaterThan(Integer [] anArray, Integer elem) { int count = 0; for (Integer e : anArray) if (e.compareTo(elem) &gt; 0) ++count; return count; } </code></pre> <p>And I use this method to compare an Integer array with the following Integer:</p> <pre><code>Integer [] numarr = {1, 2, 3, 4 , 5}; Integer num = new Integer(5); int count = Util.countGreaterThan(arrnum, num); </code></pre> <p>This seems to work fine, however if I pass a primitive array and a primitive int, it doesn't:</p> <pre><code>int [] arrnum = {1, 2, 3, 4 , 5}; int othernum = 3; int count = Util.countGreaterThan(arrnum, othernum); </code></pre> <p>The compiler complains with:</p> <pre><code>method countGreaterThan in class Generics.Util cannot be applied to given types; required: Integer[],Integer found: int[],int reason: no instance(s) of type variable(s) Integer exist so that argument type int conforms to formal parameter type Integer </code></pre> <p>The tutorials seemed to be pretty adamant that Java will always autobox/unbox objects and primitives as necessary and yet it won't do it in this particular case, what am I missing?</p> <p>Also what could be a good way to generalise this comparing method as much as possible? If I used T instead of Integer, then it would look for a T object, rather than whatever I pass to it.</p> <p>I apologise if the post is confusing and if I seem pretty ignorant about the stuff I talk about above, it's just that I've been working primarily as a perl programmer (and not as particularly experienced one either) and generalising there seems as less of an issue (due to the lack of type enforcement).</p> <p>Thanks in advance!</p>
 

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