ZakTaccardi
ZakTaccardi

Reputation: 12467

How to use generics to combine duplicate methods with a parameter that has different Java Collections containing the same class type?

The below two methods have the exact same code underneath. Is there way to decrease code duplication by using Java Generics here to combine them into a single method?

public static List<String> convert(List<Magic> magicStrings);

Note, RealmList<E> extends List<E>.

public static List<String> convert(RealmList<Magic> magicStrings);

Upvotes: 0

Views: 130

Answers (2)

rgettman
rgettman

Reputation: 178263

If the two methods have the exact same code, then there is no point in keeping the method with the more specific parameter.

Remove the convert method that takes a RealmList. Any code that wants to call convert, with a RealmList or any other kind of List, can use the convert method that takes a List.

Upvotes: 4

Jean Logeart
Jean Logeart

Reputation: 53829

If RealmList<E> extends List<E>, just delete convert(RealmList<Magic> magicStrings);

Then convert(someRealmList) will actually use the convert(List<Magic> magicStrings) implementation.

Upvotes: 2

Related Questions