没有toString方法:打印的是集合元素的内存地址
Student.java
package com.yikuan.test; public class Student { private String name; private int age; /*构造方法*/ public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } /*toSting方法*/ // @Override // public String toString() { // return "Student [name=" + name + ", age=" + age + "]"; // } /*get、set方法*/ public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Test.java
package com.yikuan.test; import java.util.ArrayList; public class Test1 { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student("aa",12)); list.add(new Student("ww",14)); list.add(new Student("qq",15)); list.add(new Student("ee",51)); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } }
结果:
com.yikuan.test.Student@2a139a55
com.yikuan.test.Student@15db9742
com.yikuan.test.Student@6d06d69c
com.yikuan.test.Student@7852e922
加上toString:打印集合中的元素值
结果:
Student [name=aa, age=12] Student [name=ww, age=14] Student [name=qq, age=15] Student [name=ee, age=51]