What is the difference between returning a type in Java and using generic T and object?

Source: Internet
Author: User

Recently, when I read the Jackson source, I found that there was a code return type written by <T> T, and I wrote it by object. Search the Internet for this syntax sugar, find a relatively simple explanation on the StackOverflow, carry over (Https://stackoverflow.com/questions/5207115/java-generics-t-vs-object)

Question: What are the differences between the declarations of the following 2 methods

 Public object DoSomething (Object obj) {...}  public <T> t dosomething (t t) {...}

Answer:

Single from the above 2 method declarations-no difference. Either t or obj, you can only invoke parameters and return values of type object.

But based on the 2 methods above, if you have a class that uses generics:

New myclass<foo>new Foo ();

You can write it like this:

Foo newfoo = my.dosomething (foo);

But if you use object, you have to write this.

Foo Newfoo = (foo) my.dosomething (foo);

Thus, using generics, there are 2 benefits:

1. No forced type conversions required

2. More secure at compile time. If you use the object class, you cannot guarantee that the returned type must be Foo, perhaps other types. At this point you will get a type conversion exception at run time (classcastexception)

What is the difference between returning a type in Java and using generic T and object?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.