泛型构造函数在Java中的用途是什么?

编程入门 行业动态 更新时间:2024-10-26 02:25:25
本文介绍了泛型构造函数在Java中的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

class Foo< T>所有人都知道您可以在Java中使用泛型类。 { T tee; Foo(T tee){ this.tee = tee;

但是你也可以使用通用的构造函数,这意味着构造函数显式接收自己的泛型类型参数,例如: ; U>酒吧(你){ //为什么!? } }

我在努力理解用例。这个功能让我做什么?

解决方案

这个功能让我能做什么?

至少有三件事可以让你做,否则你无法做:

  • 表示参数类型之间的关系,例如:

    class Bar {< T> Bar(T对象,Class< T>类型){ //'type'必须表示'object'可赋值的类, //尽管不一定是'object'的精确类。 // ... } }

  • < withdrawn>

  • 由于@Lino首先观察到,它可以让你表达参数必须与两个或更多不相关类型的组合兼容(可以当最多只有一个是接口类型时才有意义)。查看Lino的答案举例。

    As everyone knows you can have a generic class in Java by using type arguments:

    class Foo<T> { T tee; Foo(T tee) { this.tee = tee; } }

    But you can also have generic constructors, meaning constructors that explicitly receive their own generic type arguments, for example:

    class Bar { <U> Bar(U you) { // Why!? } }

    I'm struggling to understand the use case. What does this feature let me do?

    解决方案

    What does this feature let me do?

    There are at least three two things it lets you do that you could not otherwise do:

  • express relationships between the types of the arguments, for example:

    class Bar { <T> Bar(T object, Class<T> type) { // 'type' must represent a class to which 'object' is assignable, // albeit not necessarily 'object''s exact class. // ... } }

  • <withdrawn>

  • As @Lino observed first, it lets you express that arguments must be compatible with a combination of two or more unrelated types (which can make sense when all but at most one are interface types). See Lino's answer for an example.

  • 更多推荐

    泛型构造函数在Java中的用途是什么?

    本文发布于:2023-11-25 17:27:10,感谢您对本站的认可!
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   用途   Java

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!