title: Using generics to create max function that returns the larger one
body: <p>In Java, how would I use generics to create a max function that takes as parameters two Comparable objects of the same type and returns the larger one?</p>
  
  <p>I tried:</p>
  
  <pre><code>public static &lt;T extends Comparable&gt; T max(T obj1, T obj2)
  {
      return ( ((obj1).compareTo(obj2) &gt;= 0) ? obj1 : obj2);
  }
  </code></pre>
  
  <p>(It returns obj1 if they are both equal.)</p>
  
  <p>The method is based on code I found at <a href="http://www.informit.com/articles/article.aspx?p=170176&amp;seqNum=3" rel="nofollow noreferrer">http://www.informit.com/articles/article.aspx?p=170176&amp;seqNum=3</a>. </p>
  
  <p>However, when I compile it I get this warning (compiling with -Xlint:unchecked):
   warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable</p>