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

查看:1021
本文介绍了如何在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

那么, ?

推荐答案

您不需要投射。 LinkedList implements 列表,因此您无需投射。

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

即使您想要将其转换为列表对象,您可以使用泛型在以下代码中:

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:

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天全站免登陆