Java泛型T vs Object [英] Java generics T vs Object

查看:122
本文介绍了Java泛型T vs Object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两种方法声明有什么不同:

  public Object doSomething(Object obj){。 ...} 

public< T> T doSomething(T t){...}

您可以/可以做些什么一个而不是另一个?我在这个网站的其他地方找不到这个问题。 解决方案

t obj 上,您只能调用 Object

但是有了上下文 - 如果你有一个泛型类:

  MyClass的<富> my = new MyClass< Foo>(); 
Foo foo = new Foo();

然后:

  Foo newFoo = my.doSomething(foo); 

与对象相同的代码

  Foo newFoo =(Foo)my.doSomething(foo); 

两个优点:$ b​​
$ b $ ul

  • 不需要强制转换(编译器将此隐藏起来)

  • 编译时间安全性可行。如果使用 Object 版本,您不能确定该方法总是返回 Foo 。如果它返回 Bar ,那么在运行时您将有一个 ClassCastException


  • I was wondering what is the difference between the following two method declarations:

    public Object doSomething(Object obj) {....}
    
    public <T> T doSomething(T t) {....}
    

    Is there something you can/would do with one but not the other? I could not find this question elsewhere on this site.

    解决方案

    Isolated from context - no difference. On both t and obj you can invoke only the methods of Object.

    But with context - if you have a generic class:

    MyClass<Foo> my = new MyClass<Foo>();
    Foo foo = new Foo();
    

    Then:

    Foo newFoo = my.doSomething(foo);
    

    Same code with object

    Foo newFoo = (Foo) my.doSomething(foo);
    

    Two advantages:

    • no need of casting (the compiler hides this from you)
    • compile time safety that works. If the Object version is used, you won't be sure that the method always returns Foo. If it returns Bar, you'll have a ClassCastException, at runtime.

    这篇关于Java泛型T vs Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆