<identifier> expected,arrayList </identifier>

时间:2013-12-08 10:36:38

标签: java arraylist

我遇到了一些java代码问题。该程序包含大约7个文件,但我会尽量保持简短。

我正在尝试使用ObjectStream将文件中的ArrayList加载到变量中。它给了我一个警告,因为所有的编译器都可以看到,是我说一个Object应该被转换为ArrayList。当然编译器不会知道文件中有哪种对象。作为编码器,我知道该文件只能由一个ArrayList组成,而不是其他任何东西。所以我在网上搜索,发现要压制警告,坚果现在它给了我错误:

Schedule.java:34: error: <identifier> expected

为了让你了解发生了什么,这里是错误发生的代码。这个错误不应该受到任何其他类的影响

import java.util.*;
import java.io.*;


public class Schedule
{
    private static ArrayList<Appointment> schedule; 
    private static File file;

    private static ObjectInputStream objIn;
    private static boolean exit;
    private static Scanner in = new Scanner(System.in);

    public static void main(String[] args)
    {
        initializeSchedule();
        System.out.println("Welcome!");
        while(!exit){
            System.out.print("write command: ");
            Menu.next(in.next());
        }
    }

    public static void initializeSchedule()
    {
        try{
            file = new File("Schedule.ca");
            if(!file.exists()){
                schedule = new ArrayList<Appointment>();
            }
            else{
                objIn = new ObjectInputStream(new FileInputStream("Schedule.ca"));
                @SuppressWarnings("unchecked")
                schedule = (ArrayList<Appointment>)objIn.readObject();  
                objIn.close();
            } 
        } catch (IOException e){
            System.out.println("Exception thrown  :" + e);
        } catch (ClassNotFoundException e){
                System.out.println("Exception thrown  :" + e);
        }   
    }

    public static void exit()
    {
        exit = true;
    }

    public static ArrayList<Appointment> getSchedule()
    {
        return schedule;
    }

}

错误发生在initializeSchedule中,正好位于抑制之下,其中schedule设置为ObjectStream输入。

2 个答案:

答案 0 :(得分:2)

@SuppressWarnings("unchecked")的正确位置

  

TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE

因此编译器此时无法解析@SuppressWarnings,但认为它是一个语句。如果将其移到方法声明之上或时间表之上,则应该没问题。

更好的解决方法是实际纠正编译器抱怨的问题:

final Object input = objIn.readObject();
if (input instanceof ArrayList) {
  schedule = (ArrayList<Appointment>) input;
} else {
  throw new IllegalStateException(); // or whatever suits you
}

答案 1 :(得分:1)

您无法为作业添加注释。移动

@SuppressWarnings("unchecked")

到方法开始前的那一行。