首页 > 解决方案 > 类型安全:ArrayList 类型的表达式需要未经检查的转换才能符合 ArrayList? 这会引发 ClassCastException

问题描述

我对 Java 还是很陌生,需要帮助解决我的问题。

我正在尝试编写一种方法来反序列化我调用的对象Student。方法如下:

   public void readStudentInfo() {
            // Desrializes the student objects into an ArrayList for you to compare against

            try{
                FileInputStream fis = new FileInputStream("student.ser");
                ObjectInputStream ois = new ObjectInputStream(fis);

                deserializedStudents = (ArrayList) ois.readObject();

                ois.close();
                fis.close();

            }
            catch(IOException ioe){
                ioe.printStackTrace();
                return;
            } catch(ClassNotFoundException c){
                System.out.println("Class not found");
                c.printStackTrace();
                return;
            }

            for(Student student : deserializedStudents){
                System.out.println(student.toString());
            }
            }

它使用的学生类如下:

import java.io.Serializable;

public class Student implements Serializable{
    
    private static final long serialVersionUID = 1L;

    // Class Attributes
    private String studentID;
    private String rankings;
    private char personalityType;
    private String conflict;
    
    private String preferences;

    
    // Class Constructor

    public Student(String ID){
        this.studentID = ID;
    }
    
    public Student(String ID, String grades) {
        this.studentID = ID;
        grades = grades.trim();
        this.rankings = grades;
    }

    public Student(String ID, String ranking,char personality){
        this.studentID = ID;
        this.rankings = ranking;
        this.personalityType = personality;
    }
    
    // Accessor Methods
    public String getStudentID() {
        return this.studentID;
    }

    public String getRankings(){
        return this.rankings;
    }

    public String getPreferences(){
        return this.preferences;
    }

    public char getPersonalityType(){
        return this.personalityType;
    }

    public String getConflict(){
        return this.conflict;
    }

    //Modifier Methods

    public boolean setPreferences(String pref){
        this.preferences = pref;
        return true;
    }

    public boolean setGrades(String grades){
        this.rankings = grades;
        return true;
    }

    public boolean setPersonalityType(char pers){
        this.personalityType = Character.toUpperCase(pers);
        return true;
    }

    public boolean setConflict(String ids){
        this.conflict = ids;
        return true;
    }

    @Override

    public String toString(){
        return studentID + ";" + rankings + ";" + personalityType + ";" + conflict + ";" + preferences; 
    }
    

    
}


ArrayListdeserializedStudents在类的顶部启动,如下所示:ArrayList<Student> deserializedStudents = new ArrayList<>();

出于某种原因,以下行readStudentInfo()给出了此警告:类型安全:ArrayList 类型的表达式需要未经检查的转换以符合 ArrayListJava(16777748)

如果我忽略它并运行程序,该readStudentInfo()方法会给出以下错误:Exception in thread "main" java.lang.ClassCastException: class Student cannot be cast to class java.util.ArrayList (Student is in unnamed module of loader 'app'; java.util.ArrayList is in module java.base of loader 'bootstrap')

有人可以帮我理解为什么会这样吗?我尝试过几次更改以下行中的演员表deserializedStudents = (ArrayList) ois.readObject();:我还尝试在程序开始时启动 ArrayList 的地方进行一些更改,但还没有运气。

澄清:这里的基本思想是我试图将一堆 Student 类型的对象反序列化为 ArrayList 以便我可以再次使用它们。

请帮忙!

标签: javaarraylistserializationdeserializationclasscastexception

解决方案


似乎您没有序列化学生列表(这是一个自己的对象),而是一个一个地序列化学生。因此,您应该序列化一个列表,或者您应该一个一个地反序列化学生(通过不断调用 readObject())。

试试这个(使用try-with-resources):

public void readStudentInfo() {
    try (FileInputStream fis = new FileInputStream("student.ser");
            ObjectInputStream ois = new ObjectInputStream(fis)) {
        List<Student> deserializedStudents = new ArrayList<>();
        while (fis.available() > 0) {
            deserializedStudents.add((Student) ois.readObject());
        }
        deserializedStudents.foreach(student -> System.out.println(student));
    } catch(IOException | ClassNotFoundException exc){
        exc.printStackTrace();
    }        
}

推荐阅读