private static T cloneX(T x) - What does the <

2019-02-26 08:10发布

问题:

In the above declaration, what is the <T> for?

I would like to know the difference between having <T> and not having it? How does it affect the code?

回答1:

<T> here indicates the type is implied from the arguments. So:

public static <T> List<T> createList(T... args) {
  List<T> ret = new ArrayList<T>(Arrays.asList(args));
}

can be used:

List<String> list = createList("one", "two", "three");

or

List<Integer> list2 = createList(1, 2, 3);


回答2:

it just means that you will get the same class out of that method that you're putting in, to save it being Object and you having to cast all the time.



回答3:

The <T> is the Type of the parameter you're passing into that generic method.



回答4:

It is generic parameter. If you write then

string s = ...;
clone(s); // will be expanded to string clone(string x)