-2

i have created an object from a method and put that object into an array list and now i want to print the values of the object in the array list, when I use System.out.println(objectname) i get the storage location of the object instead of the values

ArrayList<Student> students = new ArrayList<Student>();

         Student tomas = new Student("tomas", "jordan");
            students.add(tomas);
            Student get = students.get(0);  
            System.out.println(get);

the result i get is Student@789ddfa3 the result i want is tomas,jordan

this is the student class below

public class Student {

public String fname;
public String lname;

//constructor
public Student(String fn,String ln){

    fname = fn;
    lname = ln;


}
}

3 Answers3

4

From this :

You should always consider overriding the toString() method in your classes.

The Object's toString() method returns a String representation of the object, which is very useful for debugging. The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes.

Because you did'nt override the toString() method herited from the Object class, you get such an output :

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

Override it in your Student class.

@Override
public String toString(){
   return fname+" "+lname;
}
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0

override toString() as

public String toString() {

return fname + lname;  
}
Encyclopedia
  • 134
  • 1
  • 9
0
Override the Object's class method toString()

import java.util.ArrayList;

public class IDInput {
public static void main(String[] args) {
    ArrayList<Student> students=new ArrayList<Student>();
    students.add(new Student("Om","Shankar"));
    System.out.println(students.get(0));
 }
}




 class Student {
    private final String mName;
    private final String lName;


    public Student(String inName, String inID) {
        mName = inName;
        lName = inID;

    }


    public String Called() {
        return (mName);
    }
    @Override
    public String toString() {

        return mName+" "+lName  ;
    }
}`enter code here`
Om S patel
  • 31
  • 2