如何在java中输出arraylist的内容?

时间:2014-03-03 22:32:33

标签: java arraylist bluej

我正在尝试在以下代码行中输出一个arraylist,但我只收到类似这样的东西@ 160eaab5

public class Company {
    static ArrayList <Employee> list1 = new ArrayList <Employee> ();
    public static void main() {
        list1.add (new Employee ("John", "Smith", 11.0));
        list1.add (new Employee ("James", "Bond", 7.0));
        list1.add (new Employee ("Fabio", "Jones", 6.9));
        list1.add (new Employee ("Simon", "Geeha", 10.0));
        output();
    }
    public static void output() {
        System.out.println("First Name\tLast Name\tSalary in thousands of dollars");
        for (int x = 0; x < list1.size(); x++) {
            System.out.println ((Employee) list1.get(x));
        }
    }
}

下面的类提供了上面arraylist的构造函数和字段。

public class Employee {
    public String first;
    public String last;
    public double money;

    public Employee (String s1, String s2, double s3) {
        first = s1;
        last = s2;
        money = s3;


    }

 }

6 个答案:

答案 0 :(得分:2)

您需要为toString()课程定义Employee方法。通过定义自定义方法,您可以根据需要使对象的String表示形式。否则,调用默认的Object#toString()实现,看起来基本上就像你发现的“ClassName @ memoryaddress”。

例如(从您上面的println推断),如果您希望Employee#toString()将员工的信息作为名字,姓氏和工资(以制表符分隔)返回,您可以这样做:< / p>

public class Employee {
    // Class members and other stuff as you have them already go here...

    @Override
    public String toString() {
        // Override the default toString() method and return a custom String instead.
        return String.format("%s\t%s\t%s", first, last, money);
    }
}

答案 1 :(得分:2)

您需要覆盖Employee Class的默认toString()方法。

答案 2 :(得分:1)

toString

添加Employee方法

对于迭代和打印,您可以使用foreach循环。

for (Employee e : list1) {
 System.out.println (e);
}

万一你想知道Employee @ 160eaab5对应的是你的Employee对象的哈希码的无符号十六进制表示。

答案 3 :(得分:1)

只需实施Employee.toString(),然后您就可以使用list1.toString()

public class Employee {
    public String first;
    public String last;
    public double money;

    public Employee (String s1, String s2, double s3) {
        first = s1;
        last = s2;
        money = s3;
    }

    @Override
    public String toString() {
       return "first=" + first + ", last=" + last + ", money=" + money;
    }
}

然后:

System.out.println(list1);

答案 4 :(得分:1)

System.out.println()只需在您的对象上调用toString()即可将其转换为String。由于您没有在Employee中重写toString(),因此调用默认的Object.toString()方法,该方法显示由hashCode()加速的对象(Employee)的类型。

答案 5 :(得分:1)

java.util.Arrays.toString(myArrayList.toArray());

这仅适用于每个元素已实现其toString()的情况。例如,对于ArrayList<Integer>,这将打印出来

[1,2,3,4,5]

因此,只要您的Employee对象具有良好的toString实现,这对您来说效果很好。