简体   繁体   English

这是转换ArrayList的好方法 <Object> 到ArrayList <MyObject> ?

[英]Is it a good way to cast ArrayList<Object> to ArrayList<MyObject>?

Based on this Spring tutorial: http://www.roseindia.net/tutorial/spring/spring3/ioc/springlistproperty.html I had a problem. 基于这个Spring教程: http : //www.roseindia.net/tutorial/spring/spring3/ioc/springlistproperty.html我遇到了问题。 i used Spring framework to create a list of objects, but I wanted to get list of list. 我使用Spring框架创建对象列表,但是我想获取列表列表。 Casting from ArrayList to ArrayList is not possible, so I've made my own static method to do it. 从ArrayList强制转换为ArrayList是不可能的,因此我使用了自己的静态方法来执行此操作。 We have two classess: 我们有两个类:

Student: 学生:

public class Student {
    private String name;
    private String address;

   //getters and setters
}

College: 学院:

import java.util.List;

public class College {
    private List<Object> list;

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }
}

And context.xml 还有context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="Student" class="testing.Student">
        <property name="name" value="Thomas"/>
        <property name="address" value="London"/>
    </bean>

    <bean id="College" class="testing.College">

        <property name="list">
            <list>
                <value>1</value>
                <ref bean="Student"/>
                <bean class="testing.Student">
                    <property name="name" value="John"/>
                    <property name="address" value="Manchester"/>
                </bean>
            </list>
        </property>
    </bean>
</beans>

Here's my main method: 这是我的主要方法:

public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext(
                "context.xml");
        College college = (College) beanFactory.getBean("College");
}

What I wanted to do here is to make generic Student ArrayList by receiving it from college object which contains Object list. 我想在这里做的是通过从包含对象列表的大学对象接收通用的Student ArrayList。 Here's my solution: 这是我的解决方案:

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;

public class MainTest {

    //This is my casting static method:

    public static ArrayList<Student> castListToStudent(College college) {
        ArrayList<Student> casted = new ArrayList<Student>();
        Student s = null;
        for (int i = 0; i < college.getList().size(); i++) {

            if (college.getList().get(i) instanceof Student) {
                s = (Student) college.getList().get(i);
                casted.add(s);
            }
        }
        return casted;
    }

    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext(
                "context.xml");
        College college = (College) beanFactory.getBean("College");
        ArrayList<Student> list = castListToStudent(college);

        for (Student s : list) {
            System.out.println(s);
        }
    }
}

Looks like it's working, but the question is - is it the best way to safely cast one list to another ? 看起来正在工作,但问题是-将清单安全地投射到另一个清单上,这是最好的方法吗?

Using Guava: 使用番石榴:

List<Object> objects = Lists.newArrayList();
objects.add("A");
objects.add("B");
List<String> strings = FluentIterable.from(objects).filter(String.class).toList();

This example returns an ImmutableList If you need a mutable list ( ArrayList ): 如果需要可变列表( ArrayList ),此示例将返回ImmutableList

List<String> strings = Lists.newArrayList(Iterables.filter(objects, String.class));

Any elements in objects that are not String (in my example) will be ignored. objects中不是String任何元素(在我的示例中)将被忽略。 This is a completely type-safe solution that does not require any self-written methods. 这是一个完全类型安全的解决方案,不需要任何自写方法。

Using an intermediate wildcard to do the casting does the job of casting. 使用中间通配符进行转换可以完成转换工作。

List<Student> casted = (List<Student>)(List<?>) college.getList();

This is more compact. 这更紧凑。 However your method is much safer as this causes an unchecked cast warning. 但是,您的方法更安全,因为这会导致未经检查的强制转换警告。

Your method is the best way to go. 您的方法是最好的方法。

Proof : List<Object> can have objects that extends Object. 证明List<Object>可以具有扩展Object的对象。 Thus if you want to cast safely, you should check that each object in List is an instance of Student. 因此,如果您想安全地进行转换,则应检查List中的每个对象都是Student的实例。 Therefore you have to traverse all the list. 因此,您必须遍历所有列表。 Thus in terms of performance you can't do any better than traversing the whole list. 因此,就性能而言,没有比遍历整个列表更好的了。

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

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