Where to put generic type

LazloFF :

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?

Peter Lustig :
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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23279&siteId=1