David Veloso
David Veloso

Reputation: 33

Filling an arraylist with Objects of two generic types

I have created a class Entry that looks like this

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

I want to make an ArrayList of this type. What should it look like?

How can I add an item1 but keep item2 null for later on? (in other words fill the array with item1s and fill in null for the item2s, the array would look like [1]Item1,null , [2]Item1, null , etc)

Upvotes: 1

Views: 681

Answers (1)

Tunaki
Tunaki

Reputation: 137084

You do it like any other list.

List is a typed-interface. Let's name its generic type T. This means our interface is List<T>. Here, we want to have a list of Entry<S, E> whatever S and E; so in this case, T = Entry<S, E>. Therefore, the list is List<Entry<S, E>>.

Sample code:

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

To take a more concrete example where S = String and E = Integer:

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

Upvotes: 2

Related Questions