本帖最后由 LINUS 于 2013-4-11 08:47 编辑
- import java.util.ArrayList;
- import java.util.Iterator;
- public class ArrayListDemo{
- public static void main (String [] args){
- ArrayList tm = new ArrayList();
- Student s1 = new Student("diaochan",1);
- Student s2 = new Student("xishi",3);
- Student s3 = new Student("yangguifei",6);
- tm.add(s1);
- tm.add(s2);
- tm.add(s3);
- Iterator it = tm.iterator();
- while(it.hasNext()){
- Student s = (Student)it.next();
- System.out.println(s);//如果不复写toString 这里直接调用get 可以么?
-
- }
- System.out.println("**************************************");
- for (int x = 0 ;x<tm.size() ;x++ ){
- Student s = (Student)tm.get(x);
- System.out.println(s.getName()+"**************"+s.getAge());//这里为什么不直接打印s呢?
- }
- }
- }
- class Student{
- private String name;
- private int age;
-
- public Student(String name,int age){
- super();
- this.name=name;
- this.age = age;
- }
- public void setName(String name){
- this.name=name;
- }
- public String getName(){
- return name;
- }
- public void setAge(int age){
- this.age = age;
- }
- public int getAge(){
- return age;
- }
- public String toString(){
- return name+"....."+age;
- }
- }
复制代码 是具体什么情况下 才考虑复写toString呢?
当我不写 get set 方法的时候
主函数直接打印 s也是可以的 为什么还需要get set方法呢?
|