如何在java中转换泛型列表类型? [英] How to cast generic List types in java?

查看:38
本文介绍了如何在java中转换泛型列表类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我需要从 LinkedList 转换为 List.有什么干净的方法可以做到这一点吗?

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

请注意,我需要将其转换为 List.没有其他类型可以.(我正在使用 Slim 和 FitNesse 开发测试夹具).

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).

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

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

所以按照Yuval A的说法,我终于把代码写成了这样.但我收到此错误:

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

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?

推荐答案

您不需要强制转换.LinkedList 实现了 List,因此您无需在此处进行转换.

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

即使您想向下转换为 ObjectList,您也可以使用以下代码中的泛型来实现:

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

现在,在您编辑之后,我明白您要做什么,如果不像这样创建新的 List,这是不可能的:

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:

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???

有关详细信息,请参阅 Sun Java 泛型教程.希望这能澄清.

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

这篇关于如何在java中转换泛型列表类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆