A<T extends B> and A <? extends B>

Refer to

http://stackoverflow.com/questions/5211548/what-is-the-difference-between-at-extends-b-and-a-extends-b

 

First of all, those are completely different constructs used in different contexts.

A<T extends B> is a part of generic type declaration such as

public class A<T extends B> { ... }

It declares generic type A with type parameter T, and introduces a bound on T, so that T must be a subtype of B.


A<? extends B> is a parameterized type with wildcard, it can be used in variable and method declarations, etc, as a normal type:

A<? extends B> a = ...; public void foo(A<? extends B> a) { ... }

Variable declaration such as A<? extends B> a means that type of a is A parameterized with some subtype of B.

转载于:https://www.cnblogs.com/chuiyuan/p/5425840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设A和B类的定义如下: ``` public class A { private String field1; private String field2; // getters and setters } public class B { private String field1; private String field2; private String field3; // getters and setters } ``` 则可以编写以下方法来实现所需的功能: ``` public static <T extends A, U extends B> void appendMissing(List<T> listA, List<U> listB, BiPredicate<T, U> matchCondition, Function<U, T> mappingFunction) { Set<T> existingItems = listA.stream().collect(Collectors.toSet()); List<T> missingItems = listB.stream() .filter(b -> !existingItems.stream().anyMatch(a -> matchCondition.test(a, b))) .map(mappingFunction) .collect(Collectors.toList()); listA.addAll(missingItems); } ``` 该方法接受三个参数: 1. `listA`:需要追加数据的A列表 2. `listB`:提供数据的B列表 3. `matchCondition`:用于匹配A和B对象的条件,使用Java 8的`BiPredicate`函数接口表示 该方法使用Java 8的流操作来执行以下步骤: 1. 将A列表转换为Set以便快速查找 2. 在B列表中过滤出所有A列表中不存在的数据 3. 将过滤出的数据转换为A对象,并收集到一个列表中 4. 将收集到的列表中的A对象追加到原始A列表的末尾 注意,`mappingFunction`参数用于将B对象转换为A对象。这是因为B对象可能包含A对象没有的其他字段,因此需要将其转换为A对象以确保类型匹配。 以下是一个示例用法: ``` List<A> listA = new ArrayList<>(); listA.add(new A("foo", "bar")); listA.add(new A("baz", "qux")); List<B> listB = new ArrayList<>(); listB.add(new B("foo", "bar", "hello")); listB.add(new B("baz", "qux", "world")); listB.add(new B("quux", "corge", "goodbye")); // Append missing B objects to A list based on field1 and field2 match appendMissing(listA, listB, (a, b) -> a.getField1().equals(b.getField1()) && a.getField2().equals(b.getField2()), b -> new A(b.getField1(), b.getField2())); // Print A list after appending missing B objects listA.forEach(a -> System.out.println(a.getField1() + ", " + a.getField2())); // Output: foo, bar | baz, qux | quux, corge ``` 在这个示例中,`appendMissing`方法使用`field1`和`field2`匹配条件将`listB`中不存在于`listA`的B对象追加到`listA`中,并将B对象转换为A对象。最终,`listA`包含三个元素:两个原始的A对象和一个从B对象转换而来的新的A对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值