在哪里放置通用类型

huangapple go评论149阅读模式
英文:

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&lt;Integer&gt; 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&lt;Integer&gt; set(ArrayList&lt;Integer&gt; 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&lt;Integer&gt; list = new ArrayList&lt;&gt;()

I would recommend to take a look at this:

https://docs.oracle.com/javase/tutorial/java/generics/why.html

huangapple
  • 本文由 发表于 2020年3月4日 08:44:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/60517554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定