加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 第二级类型参数的延迟绑定

发布时间:2020-12-15 04:56:46 所属栏目:Java 来源:网络整理
导读:这是一个人为的复制案例,但请耐心等待. 假设您要为能够将项目添加到不同类型的列表的类创建加法器接口,并具有以下行为: // Can add items to any type of array list.AdderArrayList arrayListAdder = ...;// Ok. Right list type and item types match.arr
这是一个人为的复制案例,但请耐心等待.

假设您要为能够将项目添加到不同类型的列表的类创建加法器接口,并具有以下行为:

// Can add items to any type of array list.
Adder<ArrayList> arrayListAdder = ...;
// Ok. Right list type and item types match.
arrayListAdder.add(new ArrayList<String>(),"test");
// Ok. Right list type and item types match.
arrayListAdder.add(new ArrayList<Integer>(),3);
// Compile error. Item types do not match.
arrayListAdder.add(new ArrayList<Integer>(),"test");
// Compile error. Wrong list type although item types match.
arrayListAdder.add(new LinkedList<String>(),"test");

换句话说,我希望界面说:

An adder for an specific list type has a method ‘add’. This method takes two arguments.
The first is a list of this specific type with items of type T.
The second argument is an item of type T. The method adds the item to the list.

我尝试了不同的解决方案:

interface Adder<L extends List<?>> {
    <T> void add(L<T> list,T t);
}

但表达式L< T>在其背景下是非法的.我得到的错误信息是“类型’L’没有类型参数”.

在add方法的定义之前,我找不到将列表的类型参数保持打开的方法.有没有办法指定这个接口,还是需要更高阶的泛型或Java没有的其他东西?

解决方法

interface Adder<T,L extends List<T>> {
    void add(L list,T t);
}

class ArrayListAdder implements Adder<String,ArrayList<String>> {
    @Override
    public void add(ArrayList<String> list,String t) {
        list.add(t);
    }
}

我不认为在添加定义时可以绑定T,因为必须知道T才能声明L具有类型参数(必须以绑定或非绑定形式给出).

我相信你正在寻找相当于这个C 0x代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

template <template <typename _ElementT,typename _AllocatorT> class CollectionT>
struct Adder {
    template <typename ElementT,typename AllocatorT>
    void add(CollectionT<ElementT,AllocatorT> &collection,ElementT element);
};

struct VectorAdder : public Adder<std::vector> {
    template <typename ElementT,typename _Alloc>
    void add(std::vector<ElementT,_Alloc> &vector,ElementT element) {
        vector.push_back(element);
    }
};

int main() {
    std::vector<int> vi;
    vi.push_back(1);

    std::vector<double> vd;
    vd.push_back(1.1);

    VectorAdder va;
    va.add(vi,2); // instantiates VectorAdder::add<int,...>
    va.add(vd,2.2);  // instantiates VectorAdder::add<double,...>

    for_each(vi.begin(),vi.end(),[](int x) { std::cout << x << ' '; });
    for_each(vd.begin(),vd.end(),[](double x) { std::cout << x << ' '; });
    return 0;
}

而且我很确定在Java中这是不可能的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读