How to handle type generics for variables in Java methods? -


i'm of newbie java , i'm trying learn how use generics. can explain me what's wrong code?

import java.util.collection; import java.util.iterator;  public class generics {      /**      * @param args      */     public static void main(string[] args) {         integer = new integer(28);          integer[] b = {2, 4, 8, 16, 20, 28, 34, 57, 98, 139};              //i'd prefer int[], understand native types don't go generics          int c = which(a, b); // <--- error here, see below          system.out.println("int: "+ c);     }      static <t extends number> int which( t a, collection<t> b) {         int match = -1;         int j = 0;         (iterator<t> itr = b.iterator(); itr.hasnext();) {             t t = (t) itr.next();              if (a == t) {                  match = j;                   break;               }              j++;         }         return match;     } } 

the error: the method which(t, collection<t>) in type generics not applicable arguments (integer, integer[]).

granted, use int c = arrays.binarysearch(b, a) in particular case (sorted, comparable elements) instead of custom method which, learning exercise.

can explain i'm misunderstanding here?

an array not collection

try

static <t extends number> int which( t a, t[] b) { 

and, yanflea points, change implies (other optimizations added)

int j = 0; for(t t : b) {   if (a.equals(t)) {     return j;   }   j++; } return -1; 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -