Iterating generic array of any type in Java -
if there instance of java collection may carry primitive type, generic array, and/or iterable collection, want treat generic array iterable collection, how? e.g. following pseudo java code
list<?> list1; list1.add(new int[2]); list1.add(new string[3]); list1.add(new arraylist()); (object e : list1){ if (e instanceof iterable){ //the int[2] , string[3] not fall in case want //iterate within e } } please advise how make int[2] , string[3] fall in case.
thanks & regards, william
within loop, use appropriate array operand instanceof.
for int[]:
if (e instanceof int[]) { // ... } for object arrays (including string[]):
if (e instanceof object[]){ // ... } alternatively, when adding arrays master list, wrap each 1 in arrays.aslist(). in case, use list<list> generic instead of wildcard generic list<?> , avoid need check data type instanceof. this:
list<list> list1; list1.add(arrays.aslist(new int[2])); list1.add(arrays.aslist(new string[3])); list1.add(new arraylist()); (list e : list1){ // no need check instanceof iterable because guarantee it's list (object object : e) { // ... } } anytime you're using instanceof , generics together, it's smell may doing not quite right generics.
Comments
Post a Comment