如何在java中转换泛型List类型?

时间:2022-01-09 19:22:40

Well, I have a class Customer (no base class).

好吧,我有一个类Customer(没有基类)。

I need to cast from LinkedList to List. Is there any clean way to do this?

我需要从LinkedList转换为List。有没有干净的方法来做到这一点?

Just so you know, I need to cast it to List. No other type will do. (I'm developing a test fixture using Slim and FitNesse).

只是你知道,我需要把它投到List。没有其他类型可以做。 (我正在使用Slim和FitNesse开发测试夹具)。


EDIT: Okay, I think I need to give code examples here.

编辑:好的,我想我需要在这里给出代码示例。

import java.util.*;
public class CustomerCollection
{
    protected LinkedList<Customer> theList;

    public CustomerCollection()
    {
        theList = new LinkedList<Customer>();
    }

    public void addCustomer(Customer c){ theList.add(c); }
    public List<Object> getList()
    {
        return (List<? extends Object>) theList;
    }
}

So in accordance with Yuval A's remarks, I've finally written the code this way. But I get this error:

因此,根据Yuval A的评论,我终于以这种方式编写了代码。但我得到这个错误:

CustomerCollection.java:31: incompatible types
found   : java.util.List<capture#824 of ? extends java.lang.Object>
required: java.util.List<java.lang.Object>
        return (List<? extends Object>)theList;
               ^
1 error

So, what's the correct way to do this cast?

那么,这个演员的正确方法是什么?

9 个解决方案

#1


You do not need to cast. LinkedList implements List so you have no casting to do here.

你不需要施放。 LinkedList实现List,因此您无法在此处执行转换。

Even when you want to down-cast to a List of Objects you can do it with generics like in the following code:

即使您想要向下转换为对象列表,也可以使用泛型来执行此操作,如下面的代码所示:

LinkedList<E> ll = someList;
List<? extends Object> l = ll; // perfectly fine, no casting needed

Now, after your edit I understand what you are trying to do, and it is something that is not possible, without creating a new List like so:

现在,在您编辑之后,我了解您正在尝试做什么,并且这是不可能的,而不是像这样创建一个新的List:

LinkedList<E> ll = someList;
List<Object> l = new LinkedList<Object>();
for (E e : ll) {
    l.add((Object) e); // need to cast each object specifically
}

and I'll explain why this is not possible otherwise. Consider this:

我会解释为什么这是不可能的。考虑一下:

LinkedList<String> ll = new LinkedList<String>();
List<Object> l = ll; // ERROR, but suppose this was possible
l.add((Object) new Integer(5)); // now what? How is an int a String???

For more info, see the Sun Java generics tutorial. Hope this clarifies.

有关更多信息,请参阅Sun Java泛型教程。希望这澄清一下。

#2


Here's my horrible solution for doing casting. I know, I know, I shouldn't be releasing something like this into the wild, but it has come in handy for casting any object to any type:

这是我做铸造的可怕解决方案。我知道,我知道,我不应该将这样的东西发布到野外,但是将任何对象转换为任何类型都会派上用场:

public class UnsafeCastUtil {

    private UnsafeCastUtil(){ /* not instatiable */}

    /**
    * Warning! Using this method is a sin against the gods of programming!
    */
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object o){
        return (T)o;
    }

}

Usage:

Cat c = new Cat();
Dog d = UnsafeCastUtil.cast(c);

Now I'm going to pray to the gods of programming for my sins...

现在我要为我的罪孽向编程之神祈祷......

#3


I did this function for that, ugly but it works

我为此做了这个功能,丑陋但它有效

public static <T> Collection<T> cast(Collection<? super T> collection, Class<T> clazz){
    return (Collection<T>)collection;
}

#4


>    public List<Object> getList()

Why are you returning List<Object>? You might as well return List (without generics) since that is equivalent but would make the following code work:

你为什么要返回List ?您也可以返回List(没有泛型),因为这是等效的,但会使以下代码工作:

LinkedList<Customer> theList = new LinkedList<Customer>();

public List getList() {
    return theList;
}

Casting between Lists with different generic types is tricky and seems unnecessary here.

在具有不同泛型类型的列表之间进行转换是棘手的,在这里似乎没有必要。

Of course you should be returning type List<Customer> ...

当然你应该返回类型List ...

#5


LinkedList implements List, so you can implement

LinkedList实现List,因此您可以实现

List< String > list1 = new LinkedList< String >(); 

Or do you want to cast from LinkedList< String > to List< int >? in this case you have to pick every single element and convert it to an integer.

或者您想从LinkedList 转换为List ?在这种情况下,您必须选择每个元素并将其转换为整数。

#6


You should return a List<?> from your method. Intuitively, getList() returns a list so that the caller can retrieve the items inside. List<?> (which is equivalent to List<? extends Object>) allows that functionality. However, you won't be able to put anything into it via the returned list, because that would not be type safe; but I don't think that is what you need anyway.

您应该从方法返回List 。直观地,getList()返回一个列表,以便调用者可以检索其中的项。 List (相当于List )允许该功能。但是,您将无法通过返回的列表将任何内容放入其中,因为这不是类型安全的;但我不认为这是你需要的。

public List<?> getList()
{
    return theList;
}

#7


just put

public static List<Object> getList() {
    List l = test;
    return l;
}

#8


If your list is of a generic type for eg

如果您的列表是通用类型,例如

ArrayList<String> strList = new ArrayList<String>(); strList.add("String1"); Object o = strList;

ArrayList strList = new ArrayList (); strList.add( “字符串1”); Object o = strList;

then Following method should work

然后下面的方法应该工作

public <T> List<T> getListObjectInBodyOfType(Class<T> classz, Object body) {
    if(body instanceof List<?>){
        List<?> tempList = (List<?>)body;
        if(tempList.size() > 0 && tempList.get(0).getClass().equals(classz)){
            return (List<T>) body;
        }
    }
    return new ArrayList<T>();
}

How to use it?

如何使用它?

List<String> strList1 = getListObjectInBodyOfType(String.class, o);

as I mentioned before it works if the Object contains generic list, this won't work if you pass a non-generic list with mixed type of elements

正如我之前提到的,如果Object包含泛型列表,它将起作用,如果传递具有混合类型元素的非泛型列表,这将不起作用

#9


List is an interface, LinkedList is a concrete implementation of that interface. Much of the time an implicit cast will work, assign a LinkedList to a List, or pass it to a function expecting a List and it should just `work'.

List是一个接口,LinkedList是该接口的具体实现。很多时候隐式转换会起作用,将LinkedList分配给List,或者将它传递给期望List的函数,它应该只是“工作”。

An explicit cast can also be done if necessary.

如有必要,也可以进行显式演员表。

//This is valid
List<Customer> myList = new LinkedList<Customer>();

//Also Valid
List<Customer> myList = (List<Customer>) new LinkedList<Customer>();

#1


You do not need to cast. LinkedList implements List so you have no casting to do here.

你不需要施放。 LinkedList实现List,因此您无法在此处执行转换。

Even when you want to down-cast to a List of Objects you can do it with generics like in the following code:

即使您想要向下转换为对象列表,也可以使用泛型来执行此操作,如下面的代码所示:

LinkedList<E> ll = someList;
List<? extends Object> l = ll; // perfectly fine, no casting needed

Now, after your edit I understand what you are trying to do, and it is something that is not possible, without creating a new List like so:

现在,在您编辑之后,我了解您正在尝试做什么,并且这是不可能的,而不是像这样创建一个新的List:

LinkedList<E> ll = someList;
List<Object> l = new LinkedList<Object>();
for (E e : ll) {
    l.add((Object) e); // need to cast each object specifically
}

and I'll explain why this is not possible otherwise. Consider this:

我会解释为什么这是不可能的。考虑一下:

LinkedList<String> ll = new LinkedList<String>();
List<Object> l = ll; // ERROR, but suppose this was possible
l.add((Object) new Integer(5)); // now what? How is an int a String???

For more info, see the Sun Java generics tutorial. Hope this clarifies.

有关更多信息,请参阅Sun Java泛型教程。希望这澄清一下。

#2


Here's my horrible solution for doing casting. I know, I know, I shouldn't be releasing something like this into the wild, but it has come in handy for casting any object to any type:

这是我做铸造的可怕解决方案。我知道,我知道,我不应该将这样的东西发布到野外,但是将任何对象转换为任何类型都会派上用场:

public class UnsafeCastUtil {

    private UnsafeCastUtil(){ /* not instatiable */}

    /**
    * Warning! Using this method is a sin against the gods of programming!
    */
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object o){
        return (T)o;
    }

}

Usage:

Cat c = new Cat();
Dog d = UnsafeCastUtil.cast(c);

Now I'm going to pray to the gods of programming for my sins...

现在我要为我的罪孽向编程之神祈祷......

#3


I did this function for that, ugly but it works

我为此做了这个功能,丑陋但它有效

public static <T> Collection<T> cast(Collection<? super T> collection, Class<T> clazz){
    return (Collection<T>)collection;
}

#4


>    public List<Object> getList()

Why are you returning List<Object>? You might as well return List (without generics) since that is equivalent but would make the following code work:

你为什么要返回List ?您也可以返回List(没有泛型),因为这是等效的,但会使以下代码工作:

LinkedList<Customer> theList = new LinkedList<Customer>();

public List getList() {
    return theList;
}

Casting between Lists with different generic types is tricky and seems unnecessary here.

在具有不同泛型类型的列表之间进行转换是棘手的,在这里似乎没有必要。

Of course you should be returning type List<Customer> ...

当然你应该返回类型List ...

#5


LinkedList implements List, so you can implement

LinkedList实现List,因此您可以实现

List< String > list1 = new LinkedList< String >(); 

Or do you want to cast from LinkedList< String > to List< int >? in this case you have to pick every single element and convert it to an integer.

或者您想从LinkedList 转换为List ?在这种情况下,您必须选择每个元素并将其转换为整数。

#6


You should return a List<?> from your method. Intuitively, getList() returns a list so that the caller can retrieve the items inside. List<?> (which is equivalent to List<? extends Object>) allows that functionality. However, you won't be able to put anything into it via the returned list, because that would not be type safe; but I don't think that is what you need anyway.

您应该从方法返回List 。直观地,getList()返回一个列表,以便调用者可以检索其中的项。 List (相当于List )允许该功能。但是,您将无法通过返回的列表将任何内容放入其中,因为这不是类型安全的;但我不认为这是你需要的。

public List<?> getList()
{
    return theList;
}

#7


just put

public static List<Object> getList() {
    List l = test;
    return l;
}

#8


If your list is of a generic type for eg

如果您的列表是通用类型,例如

ArrayList<String> strList = new ArrayList<String>(); strList.add("String1"); Object o = strList;

ArrayList strList = new ArrayList (); strList.add( “字符串1”); Object o = strList;

then Following method should work

然后下面的方法应该工作

public <T> List<T> getListObjectInBodyOfType(Class<T> classz, Object body) {
    if(body instanceof List<?>){
        List<?> tempList = (List<?>)body;
        if(tempList.size() > 0 && tempList.get(0).getClass().equals(classz)){
            return (List<T>) body;
        }
    }
    return new ArrayList<T>();
}

How to use it?

如何使用它?

List<String> strList1 = getListObjectInBodyOfType(String.class, o);

as I mentioned before it works if the Object contains generic list, this won't work if you pass a non-generic list with mixed type of elements

正如我之前提到的,如果Object包含泛型列表,它将起作用,如果传递具有混合类型元素的非泛型列表,这将不起作用

#9


List is an interface, LinkedList is a concrete implementation of that interface. Much of the time an implicit cast will work, assign a LinkedList to a List, or pass it to a function expecting a List and it should just `work'.

List是一个接口,LinkedList是该接口的具体实现。很多时候隐式转换会起作用,将LinkedList分配给List,或者将它传递给期望List的函数,它应该只是“工作”。

An explicit cast can also be done if necessary.

如有必要,也可以进行显式演员表。

//This is valid
List<Customer> myList = new LinkedList<Customer>();

//Also Valid
List<Customer> myList = (List<Customer>) new LinkedList<Customer>();