-3

There are two classes, one is Student and the other one is Array_list. There is a problem with the output am not able to understand instead of showing name and sex it shows "Student@9e0bfd"

class Student {
    String name;
    String sex;
    Student(String name String sex)
    {
        this.name=name;
        this.sex=sex;
    }
}

SECOND CLASS

import java.util.*;

class Array_list {
    public static void main (String args []) {
        ArrayList<Student> list=new ArrayList<Student>();
        Student s1=new Student("ashish ","male");
        list.add(s1);
        Iterator itr =list.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}
dsh
  • 12,037
  • 3
  • 33
  • 51
user187744
  • 71
  • 1
  • 1
  • 7
  • You need to override the `toString()` method in class `Student` so that it prints what you want instead of something like "Student@9e0bfd". – Jesper Sep 14 '15 at 13:37
  • Like others have said, the `toString()` method is what defines what is printed when you do `System.out.println()` on an object. The default `toString()` method shows the object class and its hash code so that you can see differentiate your different object instances apart. Since it is also used by default in error messages, this makes quite a bit of sense. – Saad Sep 14 '15 at 13:41
  • you are also missing `,` in contructor for parameter separator. – Rustam Sep 14 '15 at 13:42
  • If I use something like this "Student st=(Student)itr.next(), system.out.print (st.name+""st.sex)"then the output is correct but am not able to understand why – user187744 Sep 14 '15 at 13:50
  • If I use something like "Student st=(Student )itr.next().System.out.println (st.name +""st.sex);" then everything works fine. I am unable to understand why so? – user187744 Sep 14 '15 at 14:00

1 Answers1

1

In your student class, you will need to override toString() to return the data you want to display.

akodiakson
  • 779
  • 1
  • 5
  • 10