Reputation: 673
I have a problem with an implementation of ArrayLists - I try to print my objects, but right now it only prints the memory adresses. I figure a loop is my savior somehow, but can't for the love of... figure out how to loop through my Course objects to make that happen. What am I missing? It can't be impossible or anything, it's just me being to stupid to figure it out (my forehead has a permanent imprint of my keyboard now).
public class Course{
private String courseID;
private String courseName;
private int ap;
private static ArrayList<Course> courses = new ArrayList<Course>();
public static void main(String[] args) {
Course programmeringGrund = new Course ("725G61", "Programmering Grundkurs", 6);
Course itProjekt = new Course ("725G62", "IT-Projektledning - introduktion", 12);
Course diskretMatematik = new Course ("764G06", "Diskret Matematik och Logik", 6);
Course informatikTeknik = new Course ("725G37", "Informatik, teknik och lärande", 6);
System.out.println(getCourses());
} public Course (String aCourseID, String aCourseName, int anAp){
this.courseID=aCourseID;
this.courseName=aCourseName;
this.ap=anAp;
courses.add(this);
} public static List getCourses(){
return courses;
}
Upvotes: 0
Views: 1125
Reputation: 1926
You have two options:
Traverse the List
returned by getCourses()
and print out values for each course object
. Something like
ArrayList<Course> mycourses = getCourses();
for(Course obj: mycourses)
{
System.out.println("Id is "+obj.courseId);// So on you print everything
}
OR You can override the toString()
Method in you Course
class as ZouZou mentioned. As you haven't over ridden the toString()
method as of now it is printing the memory address for the List
Upvotes: 0
Reputation: 8960
public class Course
{
...
@Override
public String toString()
{
return "ID=" + courseID + ", Name=" + courseName;
}
...
}
Upvotes: 0
Reputation: 178263
You need to override the toString()
method in Course
. The "memory address" printed is part of Object
's toString()
method, and you haven't overridden toString()
.
Upvotes: 2