0

So I have an interface

public interface Identity {

abstract void setKey(String key);
abstract String getKey();
}

That I want to use for an insert sort function

public static void InsertIdentity(Identity identity, ArrayList<? extends Identity> list) {
    int i = 0;
    Identity id;
    while (i < list.size()) {
        if ((id = list.get(i)).getKey().compareTo(identity.getKey()) < 0) {
            i++;
        }else{break;}
    }
    list.add(i, identity);
}

But obviously I cannot add an Identity to a ArrayList - ? extends Identity

I was wondering if there is a way around this?

I know Java has other ways of doing this task but I would like this function to work.

TheOnlyWAR10CK93
  • 113
  • 1
  • 10
  • Possible duplicate of [Java generic collection, cannot add list to list](http://stackoverflow.com/questions/16305164/java-generic-collection-cannot-add-list-to-list). And there are many more questions dealing with this issue ... – Seelenvirtuose Apr 23 '15 at 08:50
  • I know why it doesn't work, I was hoping someone could help me find a way around it – TheOnlyWAR10CK93 Apr 23 '15 at 08:50
  • The way around it is to not declare your parameter with an upper bounded wildcard. – Seelenvirtuose Apr 23 '15 at 08:52
  • But then it defeats the purpose of the function – TheOnlyWAR10CK93 Apr 23 '15 at 08:53
  • You obviously want to make your method work on _various types_. This cries for a type parameter: ` void insertIdentity(T identitiy, List list) { ... }`. By the way: Keep on using Java's code conventions, and use interfaces where appropriate. – Seelenvirtuose Apr 23 '15 at 08:56

3 Answers3

4

You could make the method generic:

public static <T extends Identity> void InsertIdentity(T identity, ArrayList<T> list) {
    //...

You may need to make other methods generic as well, if you use this approach.

fabian
  • 80,457
  • 12
  • 86
  • 114
3

I would suggest the following:

public static <I extends Identity> void InsertIdentity(I identity, ArrayList<I> list) 
Blip
  • 3,061
  • 5
  • 22
  • 50
2

This can work, depending on how you will use the InsertIdentity method:

public static <T extends Identity> void InsertIdentity(T identity, ArrayList<T> list) {