| Author |
about generic method and the vars arg
|
Helen Ma
Ranch Hand
Joined: Nov 01, 2011
Posts: 319
|
|
This is a mock exam question from Mughal and Rasumansse's book:
public class Vars {
public static <E > void print(E e, E...src){
for (E elt: src){
System.out.print(elt +"|");
}
System.out.println( );
}
public static void main (String...strings ){
String[] sa ={"9","6"};
print (sa, "9","6");
}
}
The output is |9|6.
But my question is E e is a String[] type in this case. Therefore E...src must be String[]...src .
However, in this quiz, "9", "6" are two String being passed to print method."6" and "9" are String, but not String[].
Why does it still compiled?
|
 |
Helen Ma
Ranch Hand
Joined: Nov 01, 2011
Posts: 319
|
|
Another funny thing is that :
public class Vars {
public static <E > void print(E e, E src){
System.out.println(src );
}
public static void main (String...strings ){
String[] sa ={"9","6"};
print ("0", new Integer(1));
}
}
I modified the question a little bit, I pass a String "0" as the e , the an Integer as the src. I thought E e and E src must have the same type. But the compiler compiles the E as an object since E does not extends any type , like <E extends Integer> or <E extends String>.
To answer my previous question ,
I think print (sa, "9", "6") are compiles as sa is an object, "9" is an object and "6" is an object. E ... src is Object[] src = {"9" , "6"}
Correct me if I am wrong.
|
 |
Glen Iris
Ranch Hand
Joined: Jul 13, 2011
Posts: 69
|
|
Hi Helen,
Firstly, when you quote code you should place it in code tags - it just makes it easier to read.
To answer your first question,
void helensMethod(String...src){}
helensMethod can be invoked by using:
or
or
We can pass helensMethod any number of Strings (as long as that number >= 1.
Ie - when you use var agrs in the method signature you can pass 1 or more of the type amount to the method.
To answer your second question:
It is acceptable to pass an Integer and a String as the var args. Although they are different types, they both extend Object.
|
OCPJP 6
|
 |
Helen Ma
Ranch Hand
Joined: Nov 01, 2011
Posts: 319
|
|
Hi, This quiz is about generic and var args.
I just noticed something about generic. I have the following code
E has to be the same. So, I should pass in List<Animal> e and List<Animal> e1 as parameters. If I pass in List<Animal> e and List<Dog> e1 , it won't compile.
But in the quiz, the code is like this:
E is an object type. Therefore I can pass a String as e and Integer as e1. e and e1 may not have the same type, unlike the above List<E> e example.
So,my conclusion is that print (sa, "9", "6") means passing sa , the String[] sa = {"9","6"} and passing "9" and "6" as the string var arguments.
The "9" and "6" will be put inside the String array. (E... e1 is compiled as E[] e1).
Before, I misunderstood that if E e is a string[], e1 has to be a string[] too.
|
 |
 |
|
|
subject: about generic method and the vars arg
|
|
|