java - How to call to LinkedList with generic type -
i'm using several linkedlist
each 1 different type, example :
linkedlist<a> typea = new linkedlist<>(); linkedlist<b> typeb = new linkedlist<>(); linkedlist<c> typec = new linkedlist<>();
and want print them according type, each type call appropriate function.
void funca(linkedlist<a> ls) void funcb(linkedlist<b> ls) void funcc(linkedlist<c> ls)
and wonder if option of calling 1 function , inside function check type. thank help! have nice day :)
you use unbound generic type in list parameter of method, follow:
public static void main(string[] args) { list<string> liststr = arrays.aslist("a","b","c"); list<integer> listint = arrays.aslist(1,2,3); printlist(liststr); printlist(listint); } private static void printlist(list<?> list) { for(object obj : list){ if(obj instanceof string){ string str = (string) obj; system.out.printf("string: %s \n", str); } else if(obj instanceof integer){ integer integer = (integer) obj; system.out.printf("integer: %s \n", integer); } } }
Comments
Post a Comment