I've created a list from objects from my user defined class called students.
class Student {
String name, phone, group;
Student(String name, String phone, String group) {
this.name = name;
this.phone = phone;
this.group = group;
}
}
And accessed it in the following way:
public static void main(String[] args) {
Student s1 = new Student("Ayush", "9841293412", "L1N1");
Student s2 = new Student("Rahul", "9842432423", "L1M1");
Student s3 = new Student("Gaurav", "984129231", "L1N2");
ArrayList<Student> al = new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
al.add(s4);
al.add(s5);
for(Student name:al){
System.out.println("Name: " + name);
}
But the output is referencing object like following:
Name: Student@1baf61
Name: Student@b5272
I don't know why this has happened.
Just extract the name field instead:
class Student {
String name, phone, group;
Student(String name, String phone, String group) {
this.name = name;
this.phone = phone;
this.group = group;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
", group='" + group + '\'' +
'}';
}
public static void main(String[] args) {
Student s1 = new Student("Ayush", "9841293412", "L1N1");
Student s2 = new Student("Rahul", "9842432423", "L1M1");
Student s3 = new Student("Gaurav", "984129231", "L1N2");
ArrayList<Student> al = new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
for (Student name : al) {
System.out.println("Name: " + name.name);
System.out.println("Name: " + name.getName()); // Using a getter
System.out.println(name); // Using toString
}
}
}
As a best practice use a getter or a toString implementation to better represent your model
You can override the toString method in your StudentClass or if u want only the name you can implement a getter method in your StundentClass..
class Student {
String name, phone, group;
Student(String name, String phone, String group) {
this.name = name;
this.phone = phone;
this.group = group;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
", group='" + group + '\'' +
'}';
}
usage toString
for(Student name:al){
System.out.println("Name: " + name);
}
output:
Name: Student{name='Ayush', phone='9841293412', group='L1N1'}
Name: Student{name='Rahul', phone='9842432423', group='L1M1'}
Name: Student{name='Gaurav', phone='984129231', group='L1N2'}
usage of your getter
for(Student name:al){
System.out.println("Name: " + name.getName());
}
output:
Name: Ayush
Name: Rahul
Name: Gaurav
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.