【问题标题】:Arraylist output is not coming out as intendedArraylist 输出未按预期输出
【发布时间】:2014-10-07 00:10:59
【问题描述】:

请原谅我的格式,我是编码和这些板的新手。我正在尝试制作一个简单的待办事项列表作为java中的练习。它从文本文件中读取和解析数据,然后对其进行排序和打印。

我的输出如下所示: [ToDoList003_002.ToDo@4cc7014c] 输出应该是这样的:[get milk,important,highpriority,urgent]

package ToDoList003_002;


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


public class ToDoList002 {
ArrayList<ToDo> toDoList=new ArrayList<ToDo>();

public static void main(String[] args) {

    new ToDoList002().go();
}//close main

    public void go(){
        getItems();
        Collections.sort(toDoList); //002
        System.out.println(toDoList);

    }

    void getItems(){
        try{
            File file=new File("/Users/lew/Dropbox/JAVA/CodePractice/src/ToDoList003_002/todolist.txt");
            BufferedReader reader = new BufferedReader (new FileReader(file));
            String line=null;
                while ((line=reader.readLine()) !=null){
                    addItem(line);
                }
        }catch(Exception ex){
                    ex.printStackTrace();
                }



    }

    void addItem(String lineToParse){
        String[] tokens=lineToParse.split("/");
        //toDoList.add(tokens[0]);
        //toDoList.add(tokens[1]);
        ToDo nextTodo= new ToDo(tokens[0], tokens[1],tokens[2],tokens[3]);
        toDoList.add(nextTodo);
    }



    //private static void add(String string) {
        // TODO Auto-generated method stub

    }





package ToDoList003_002;

import java.util.ArrayList;

public class ToDo implements Comparable<ToDo>{
String detail;
String importance;
String priority;
String urgency;

public int compareTo (ToDo d){
    return detail.compareTo(d.getDetail());
}

ToDo(String d, String i, String p, String u){
    detail=d;
    importance=i;
    priority=p;
    urgency=u;
    //set variables in constructor
}
public String getDetail(){
    return detail;
}

public String getImportance(){
    return importance;
}

public String getPriority(){
    return priority;
}

public String getUrgency(){
    return urgency;

public String toString(){
    return detail;  
}   

【问题讨论】:

  • 该代码似乎在ToDo 类中包含toString() 方法,但由于语法错误,不能复制粘贴实际代码。
  • 到目前为止我已经尝试了 6 个答案,而那些编译的答案仍然给我哈希值。我注意到我在 Eclipse 中的 toString() 上遇到了一些错误:此行有多个标记.....语法错误,插入 enumbody 以完成块语句....语法错误令牌“字符串”@预期...语法错误, 插入“枚举标识符”以完成 enumHeaderName
  • 好吧,我真的仔细看了一遍,发现一个杂散的括号影响了我的 tostring。修复后,覆盖帮助了谢谢!

标签: java eclipse arraylist


【解决方案1】:

您可以使用for-each 循环来打印列表的内容,如下所示: 注意:您必须覆盖 toString()ToDo 类并使用它

   public static void main(String[] args) {
    List<String> ls = new ArrayList<String>(); // use ToDo instead of String here
    ls.add("a");
    ls.add("b");
    ls.add("c");
    for (String s : ls) {
        System.out.println(s);
    }
}

O/P

a
b
c

像这样覆盖Todo 类的toString()

@Override
public String toString() {
    return detail + "," + importance ; // add other fields if you want

}

【讨论】:

    【解决方案2】:

    您需要在ToDo 中覆盖toString()

    例如:

    @Override
    public String toString() {
        return detail + "," + importance + "," + priority + "," + urgency;
    }
    

    【讨论】:

      【解决方案3】:

      当您调用System.out.println(someObject); 时,您会调用该对象上的toString() 方法。 ArrayList 不会覆盖从 Object 继承的标准 toString() 方法,因此结果是 类型名称 + @ + 哈希码

      您需要在您的ToDo 列表中覆盖toString(),以便它打印得漂亮。然后采用一种方法来打印您的收藏,例如

      System.out.println(Arrays.toString(toDoList.toArray()));
      

      更多灵感请见Printing Java collections nicely

      【讨论】:

        【解决方案4】:

        这一行表明您正在将 ToDo 对象添加到列表中

        toDoList.add(nextTodo);
        

        然后您正在对对象进行排序并尝试打印它们。

        Collections.sort(toDoList);
        System.out.println(toDoList);
        

        所以首先将 Todo 对象从列表中取出,然后尝试获取该对象的值 像这样的

        for(ToDo todo : toDoList)
        {
          System.out.println(todo.getDetail()+"\t"+
                           todo.getImportance()+"\t"+
                           todo.getPriority()+"\t"+
                           todo.getUrgency());
        }
        

        【讨论】:

          【解决方案5】:

          ToDo 类应覆盖 toString 方法以提供对象的字符串表示形式

          class ToDo {
          ...
             @Override
             public String toString() {
              return this.priority + "," + ...;
             }
          ...
          }
          

          【讨论】:

            【解决方案6】:

            您需要覆盖 toString 方法。来自 oracle 文档:

            公共字符串 toString()

            返回对象的字符串表示形式。一般来说, toString 方法返回一个“以文本形式表示”的字符串 目的。结果应该是简洁但信息丰富的表示 这对一个人来说很容易阅读。建议所有 子类覆盖此方法。

            Object 类的 toString 方法返回一个字符串,该字符串由 对象是其实例的类的名称,at 符号 字符“@”和哈希的无符号十六进制表示 对象的代码。换句话说,这个方法返回一个字符串等于 值:

            getClass().getName() + '@' + Integer.toHexString(hashCode())

            返回:对象的字符串表示形式。

            toString() 实现示例:

            public final class Vehicle {
            
              private String fName = "Dodge-Mercedes"
            
              @Override public String toString() {
                StringBuilder result = new StringBuilder();
                String NEW_LINE = System.getProperty("line.separator");
                result.append(this.getClass().getName() + " Object {" + NEW_LINE);
                result.append(" Name: " + fName + NEW_LINE);
                result.append("}");
                return result.toString();
              }
            }  
            

            如果您使用的是 eclipse,您可以使用 Alt+Shift+S+S 自动为类覆盖 toString() 方法..此快捷方式在生产代码中可能没有用(它会打印出所有字段名称,从安全角度来看可能不好)但出于开发目的就足够了

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-10-27
              • 2012-02-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-09-19
              相关资源
              最近更新 更多