英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论