代码之家  ›  专栏  ›  技术社区  ›  Asif Mushtaq

泛型在参数中是如何工作的?

  •  0
  • Asif Mushtaq  · 技术社区  · 8 年前

    我有点困惑泛型是如何工作的?我正在学习 function API 在java中,我只是测试 Function compose 泛型如何工作的方法 组成

    这是我读到的方法 official docs tutorial .

    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
    

    作用 API 作者签名如下:

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
    

    1) 第一个问题 T&R声明?在返回类型和参数中使用。还是我的理解错了?

    super extends 在泛型和 read here 然后我测试 组成 方法越来越多,然后再困惑如何 超级的 延伸 工作于 方法

    public static void main(String... args){
        Function<Integer, String> one = (i) -> i.toString();
        Function<String, Integer> two = (i) -> Integer.parseInt(i);
        one.compose(two);
    }
    

    如上所述,我用lamdas声明了两个函数。一个是整数输入和字符串输出,另一个是相反的。

    2) 第二个问题 Integer String 超级的 一串 整数

    3 回复  |  直到 8 年前
        1
  •  1
  •   Sweeper    8 年前

    你在哪里 T R

    回想起 compose Function 界面它不仅可以使用自己的泛型参数,还可以使用类型的泛型参数。

    interface Function<T, R> {
        ...
    }
    

    是什么 ? extends ? super ?

    ? extends super ? super V ? 它必须是的超类 V ? extends T 意味着不管怎样 T 它本身

    现在我们来看一下:

    Function<Integer, String> one = (i) -> i.toString();
    Function<String, Integer> two = (i) -> Integer.parseInt(i);
    one.compose(two);
    

    Integer String . 是什么 五、 Function<? super V, ? extends T>

    我们可以通过替换我们传入的参数来实现这一点- Function<String, Integer> String super V Integer extends Integer

    第二个约束已经满足,而第一个约束现在表示 必须是一个超级类 一串 一串 因此不能有子类 五、 必须是 一串

    因此,您可以编写如下内容:

    Function<String, String> f = one.compose(two);
    

    Function<Integer, String> f = one.compose(two);
    

    当你创作一个 Function<Integer, String> 和a 函数(<);字符串,整数> 你不可能得到一个 函数(<);整数,字符串> 自动推断为 整数 . 但是 String super Integer 不满意,因此编译失败。现在看到约束的使用了吗?这是为了避免程序员编写没有意义的东西。约束的另一个用途是允许您执行以下操作:

    Function<A, B> one = ...
    Function<C, SubclassOfB> two  = ...
    Function<SubclassOfC, B> f = one.compose(two);
    

    一串 五、

        2
  •  1
  •   algrid    8 年前

    1) The compose 函数是 Interface Function<T,R> . 如您在该界面的文档中所见:

    类型参数:

    R-函数结果的类型

    super extends 组成 作用

    Function<ClassA, ClassB> one;
    Function<SomeSuperClassOfC, SomeSubclassOfA> two;
    

    那么打电话是有效的

    Function<ClassC, ClassB> three = one.compose(two)
    
        3
  •  0
  •   Alexey Rykhalskiy    8 年前

    interface Function<T, R> R apply (T) ;

    Function<Integer, String> one = new Function<Integer, String>() {
        @Override
        public String apply(Integer i) {
            return i.toString();
        }
    };
    

    现在您可以使用它:

    String resultApply = one.apply(5);
    

    推荐文章