在java中使用foreach循环时出现奇怪的错误

时间:2013-12-28 22:13:32

标签: java arraylist foreach

我正在制作一个小小的todolist程序,我得到了一个我从未有过的奇怪的错误。我有4个类:1个包含todo-data的POJO类:

public class Todo implements Comparable {
  private String title;
  private String task;
  private boolean done;

  public Todo(String title, String task) {
    this.title = title;
    this.task = task;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String newTitle) {
    title = newTitle;
  }

  public String getTask() {
    return task;
  }

  public void setTask(String newTask) {
    task = newTask;
  }

  public boolean isDone() {
    return done;
  }

  public void setDone(boolean isDone) {
    done = isDone;
  }

  public int compareTo(Object obj) {
    Todo todo = (Todo) obj;
    return getTitle().compareTo(todo.getTitle());
  }

  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Todo {\n");
    sb.append("Title: \"");
    sb.append(getTitle() + "\";\n");
    sb.append("Task:  \"");
    sb.append(getTask() + "\";\n");
    sb.append("}");
    return sb.toString();
  }
}

然后我有一个存储和加载我的待办事项的课程:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ListStorage {
  Gson gson = new GsonBuilder().setPrettyPrinting().create();
  FileWriter writer;
  BufferedReader reader;

  public void storeList(List list, String filename) throws IOException {
    String json = gson.toJson(list);
    writer = new FileWriter(filename);
    writer.write(json);
    writer.close();
  }

  public List loadList(String filename) throws FileNotFoundException {
    reader = new BufferedReader(new FileReader(filename));
    List list = gson.fromJson(reader, List.class);
    return list;
  }
}

然后我有一个'经理'课程,基本上是我的控制者:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Manager {
  private List<Todo> todos = new ArrayList<>();
  private ListStorage storage = new ListStorage();

  public List getTodos() {
    return todos;
  }

  public void setTodos(List newTodos) {
    todos = newTodos;
  }

  public ListStorage getStorage() {
    return storage;
  }

  public void add(String title, String task) {
    todos.add(new Todo(title, task));
    sort();
    try {
      storage.storeList(todos, "todos");
    } catch(Exception e) {
      e.printStackTrace();
    }   
  }

  public void remove(int index) {
    todos.remove(index);
    sort();
    try {
      storage.storeList(todos, "todos");
    } catch(Exception e) {
      e.printStackTrace();
    } 
  }

  private void sort() {
    Collections.sort(todos);
  }
}

最后我的主要类用于测试我的代码(错误似乎在这里):

class CLITodo {
  public static void main(String[] args) {
    Manager man = new Manager();

    man.add("Hello", "Bye");
    man.add("Foo",   "Bar");
    try {
      man.setTodos(man.getStorage().loadList("todos"));
    } catch(Exception e) {

    }
    java.util.List<Todo> todos = man.getTodos();
    for (Todo t : todos) {
      System.out.println(t);
    }
  }
}

我在CLITodo类中离开<Todo>时收到的错误消息是:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Todo at CLITodo.main(CLITodo.java:13)

当我在CLITodo中删除<Todo>时,我收到此错误:

CLITodo.java:13:19: error: incompatible types
    for (Todo t : todos) {
                  ^
  required: Todo
  found:    Object

为什么会出现此错误?我的经理类getTodos() - 方法返回一个类型为Todo的List但编译器告诉我它只是一个Object(当然它也是一个集合,它实际上应该工作)。 这是第一次发生此错误,我似乎无法找到导致它的原因。

1 个答案:

答案 0 :(得分:5)

当您没有指定用于反序列化JSON的嵌套类型时,就像您在此处一样

List list = gson.fromJson(reader, List.class); // All it knows is that the root json is a List

Gson使用LinkedTreeMap

你真正想要的是

List list = gson.fromJson(reader, new TypeToken<List<Todo>>(){}.getType());