0

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; 
}
1
  • Override the toString method in your Course class. Commented Dec 17, 2013 at 23:07

3 Answers 3

2

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().

Sign up to request clarification or add additional context in comments.

Comments

0
public class Course 
{
    ...

    @Override
    public String toString()
    {
        return "ID=" + courseID + ", Name=" + courseName;
    }

    ...
}

2 Comments

Could you explain your answer a bit more?
@Mark This answer is more of a completion to the answers above.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.