标题翻译
Where to put generic type
问题
我在这方面还很新,目前无法自行证明,所以假设我有这段代码:
private ArrayList<Integer> array;
public ArrayList<Integer> set(ArrayList<Integer> newArray) {
return something;
}
在方法的类型中是否应该写上 "Integer"?在方法的输入类型中也应该这样做吗?我怎么知道什么时候确切地进行这样的操作?
英文翻译
I'm new on this and at the moment I cant prove this by myself so, lets say I have this code
private ArrayList<Integer> array;
public ArrayList set(ArrayList newArray) {
return something;
}
Should I write the Integer in the method type? Should I also do it in the method input type? How can I know exactly when to do it?
答案1
得分: 1
public ArrayList<Integer> set(ArrayList<Integer> newArray) {
return something;
}
Would be correct. Usually your IDE also tells you when to add the generic type and not use the raw type. It can also tell you when you can omit the type and make use of type inference. eg.
// no type needed. Compiler can infer the type.
List<Integer> list = new ArrayList<>()
I would recommend to take a look at this:
https://docs.oracle.com/javase/tutorial/java/generics/why.html
英文翻译
public ArrayList<Integer> set(ArrayList<Integer> newArray) {
return something;
}
Would be be correct. Usually your IDE also tells you when to add the generic type and not use the raw type. It can also tell you when you can omit the type and make use of type inference. eg.
// no type needed. Compiler can infer the type.
List<Integer> list = new ArrayList<>()
I would recommend to take a look at this:
https://docs.oracle.com/javase/tutorial/java/generics/why.html
专注分享java语言的经验与见解,让所有开发者获益!
评论