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

jrh*_*ath 15 java generics casting

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

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

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


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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,根据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
Run Code Online (Sandbox Code Playgroud)

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

Yuv*_*dam 29

你不需要施放.LinkedList实现List所以你没有施法在这里做.

即使你想要向下转换ListObjects,你也可以使用泛型,如下面的代码:

LinkedList<E> ll = someList;
List<? extends Object> l = ll; // perfectly fine, no casting needed
Run Code Online (Sandbox Code Playgroud)

现在,在你编辑之后,我明白你要做什么,这是不可能的,没有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
}
Run Code Online (Sandbox Code Playgroud)

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

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???
Run Code Online (Sandbox Code Playgroud)

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


log*_*gan 19

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

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

用法:

Cat c = new Cat();
Dog d = UnsafeCastUtil.cast(c);
Run Code Online (Sandbox Code Playgroud)

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