【问题标题】:Filling an arraylist with Objects of two generic types用两种泛型类型的对象填充数组列表
【发布时间】:2016-03-17 20:32:57
【问题描述】:

我创建了一个类Entry,看起来像这样

public class Entry<S,E>{
    S Item1;
    E Item2;
    Entry(S s, E e){
        this.Item1=s;
        this.Item2=e;
    }
}

我想做一个这种类型的ArrayList。它应该是什么样子?

如何添加item1 但保留item2 null 以备后用? (换句话说,用item1s 填充数组并为item2s 填充null,数组看起来像 [1]Item1,null , [2]Item1, null 等)

【问题讨论】:

    标签: java class generics arraylist data-structures


    【解决方案1】:

    您可以像其他任何列表一样执行此操作。

    List 是一个类型化接口。我们将其泛型类型命名为T。这意味着我们的接口是List&lt;T&gt;。在这里,我们想要一个Entry&lt;S, E&gt; 的列表,无论SE;所以在这种情况下,T = Entry&lt;S, E&gt;。因此,列表为List&lt;Entry&lt;S, E&gt;&gt;

    示例代码:

    List<Entry<S, E>> list = new ArrayList<>();
    list.add(new Entry<>(item1, item2));
    list.add(new Entry<>(item1, null));
    

    举一个更具体的例子,S = StringE = Integer

    List<Entry<String, Integer>> list = new ArrayList<>();
    list.add(new Entry<>("foo", 1));
    list.add(new Entry<>("bar", null));
    

    【讨论】:

    • 是的,这正是我所困惑的,谢谢,我想太多了哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多