The difference between generic and Object of?

Generic declaration

public <T> T doSomeThing(T t){
    return t;
}

Object statement

public Object doSomeThing(Object obj){
    return obj;
}

Generic references

String result = doSomeThing("参数是String");

Object references

String result = (String)doSomeThing("参数是String");

The use of generics, there are two benefits:

1. do not need to cast

2. Compile more secure. If you use the Object class, you can not guarantee the return type must be Foo, perhaps other types. Then you get a cast exception at run time (ClassCastException)

Guess you like

Origin www.cnblogs.com/uzxin/p/12047316.html