membersound
membersound

Reputation: 86847

How to use generic method parameters in Map.Entry?

I want to create a method that takes a generic List of Map.Entry's. The key should always be of type String, the value could be anything.

Then I want to supply the entries as follows:

public void test() {
    List<Map.Entry<String, String>> strings;
    apply(strings);

    List<Map.Entry<String, Integer>> integers;
    apply(integers);
}

private void apply(List<Map.Entry<String, ?>> entry) {
}

private void apply(List<Map.Entry<String, Object>> entry) {
}

But: neither apply() methods won't work here. Sidenote: I cannot change the types of the entries. Means <String, String> and <String, Integer> must remain as is.

How can I get them into a generic apply method?

Upvotes: 2

Views: 1862

Answers (2)

Eran
Eran

Reputation: 393936

Make the apply method generic:

private <T> void apply(List<Map.Entry<String, T>> entry) {
}

Note that depending on what you wish to do within the body of apply, using the private void apply(List<? extends Map.Entry<String, ?>> entry) signature may not be sufficient.

For example, if you wish to change the value of one entry in the list to be the value of another entry.

The following won't pass compilation:

private void apply(List<? extends Map.Entry<String, ?>> entry) {
    entry.get(1).setValue (entry.get(0).getValue());
}

But this will:

private <T> void apply(List<Map.Entry<String,T>> entry) {
    entry.get(1).setValue (entry.get(0).getValue());
}

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140484

After OP's edit to the question, making it List<Map.Entry<String, Integer>> rather than Map.Entry<String, Integer>...

Add the extra bound into the parameter type:

private void apply(List<? extends Map.Entry<String, ?>> entry) {
                    //  ^-------^ here

This is necessary so the compiler can stop you putting a Map.Entry<String, Integer> into a List<Map.Entry<String, String>>, for example, which would break type safety.

Upvotes: 1

Related Questions