简体   繁体   English

如何使用通用类型调用LinkedList

[英]How to call to LinkedList with generic type

I'm using several LinkedList each one from different type, for example : 我正在使用几个LinkedList每个来自不同类型,例如:

 LinkedList<A> typeA = new LinkedList<>();
 LinkedList<B> typeB = new LinkedList<>();
 LinkedList<C> typeC = new LinkedList<>();

and then i want to print them according to the type, so for each type I call to the appropriate function. 然后我想根据类型打印它们,因此对于每种类型,我都调用适当的函数。

void funcA(LinkedList<A> ls)
void funcB(LinkedList<B> ls)
void funcC(LinkedList<C> ls)

and I wonder if the is any option of calling one function and inside that function to check the type. 我想知道是否可以选择调用一个函数并在该函数内部检查类型。 Thank for those who help! 感谢那些帮助! Have a nice day :) 祝你今天愉快 :)

As other have mentioned, you can use a generic function like: 正如其他人提到的,您可以使用通用函数,例如:

public static <T> void genericFunc(LinkedList<T> ls) { 
//you can do something with the list but 
//you do not know what T is so you can't invoke T's methods 
//(apart from those belonging to Object)
}

If you want to have additional control over the types contained in T, assuming that all your objects inherit from a base class A, then you can do: 如果您想对T中包含的类型进行其他控制,并假设所有对象都从基类A继承,则可以执行以下操作:

public static <T extends A> void genericFunc(LinkedList<T> ls) { 
   for (T t : ls){
       t.somePublicMethodOfA(); 
   }
}

I'd use another generic parameter to the function to indicate how the list is to be printed based on the type. 我将对函数使用另一个通用参数来指示如何根据类型打印列表。

See http://www.functionaljava.org/javadoc/4.7/functionaljava/fj/Show.html 参见http://www.functionaljava.org/javadoc/4.7/functionaljava/fj/Show.html

Example: 例:

void func<A>(LinkedList<A> list, Show<A> aShow) {
  listShow(aShow).printLn(list)
}

If you were using Scala you would make Show[A] an implicit parameter. 如果您使用的是Scala,则可以将Show[A]设为隐式参数。

you can use a generic method. 您可以使用通用方法。

public <T> void func(LinkedList<T> ls) { // T can be any type
   // do something
}

You could use a unbound generic type in the list parameter of the method, it would look as follow: 您可以在方法的list参数中使用未绑定的泛型类型,如下所示:

public static void main(String[] args) {
    List<String>  listStr = Arrays.asList("A","B","C");
    List<Integer> listInt = Arrays.asList(1,2,3);
    printList(listStr);
    printList(listInt);

}

private static void printList(List<?> list) {
    for(Object obj : list){
        if(obj instanceof String){
            String str = (String) obj;
            System.out.printf("String: %s \n", str);
        } else if(obj instanceof Integer){
            Integer integer = (Integer) obj;
            System.out.printf("Integer: %s \n", integer);
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM