Page 1 of 2 12 LastLast
Results 1 to 20 of 28
  1. #1
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default How to display the elements of a List as the values of a map?

    Greetings one and all.
    I hope the above question covers it, but could anyone kindly point out why the displayCDs() method in the following code displays [CD@*****] values rather than the values they are meant to!?

    Java Code:
    import java.util.*;
    import ou.*;
    
     /** Class MusicLibrary - models a simple catalogue of CDs
    
    public class MusicLibrary
    {
       private SortedMap<String, List<CD>> cdCatalogue;
       
       
       public MusicLibrary()
       {
          super();
          this.cdCatalogue = new TreeMap<String, List<CD>>();
       }
       
       public void displayCDs()
       {
          for (String eachCD : cdCatalogue.keySet())
          {
             System.out.println(cdCatalogue.get(eachCD));
          }
       }
             
       /**
        * Test method to add some CDs to a music library
        */
       public void populate()
       {
          List<CD> temp;
          temp = new ArrayList<CD>();
          temp.add(new CD("Andy Sheppard","Soft on the Inside", "Jazz",1990));
          this.cdCatalogue.put("Andy Sheppard", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Barbara Thompson","Songs from the Centre of the Earth","jazz",1991));
          this.cdCatalogue.put("Barbara Thompson", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Benjamin Britten", "Piano Concerto", "Classical",1938));
          this.cdCatalogue.put("Benjamin Britten", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Bob Dylan","Blood on the Tracks","Other", 1975));
          this.cdCatalogue.put("Bob Dylan", temp);
          this.cdCatalogue.get("Bob Dylan").add(new CD("Bob Dylan","No Direction Home", "Folk/rock",2005));
          this.cdCatalogue.get("Bob Dylan").add(new CD("Bob Dylan","Street Legal", "Folk/rock", 1978));
          temp = new ArrayList<CD>();
          this.cdCatalogue.get("Bob Dylan").add(new CD("Bob Dylan", "Blonde on Blonde", "Folk/rock", 1966));
          temp = new ArrayList<CD>();
          temp.add(new CD("Dave Brubeck Quarter", "Time Out", "Jazz",1959));
          this.cdCatalogue.put("Dave Brubeck Quartet", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Gilad Atzmon", "Rearranging the 20th Century","Jazz",2004));
          this.cdCatalogue.put("Gilad Atzmom", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Inti-Illimani", "Leyenda", "World music", 1990));
          this.cdCatalogue.put("Inti-Illimani", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("John Adams","Shaker Loops","New music",1983));
          this.cdCatalogue.put("John Adams",temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Louis Sclavis", "Les Violences de Rameau", "Jazz",1996));
          this.cdCatalogue.put("Louis Sclavis", temp);
          this.cdCatalogue.get("Louis Sclavis").add(new CD("LouisSclavis","Clarinettes","Jazz",1984));
          this.cdCatalogue.get("Louis Sclavis").add(new CD("Louis Sclavis", "Phare", "Jazz", 2005));
          temp = new ArrayList<CD>();
          temp.add(new CD("Miles Davies", "Porgy and Bess", "Jazz", 1958));
          this.cdCatalogue.put("Miles Davies", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("Mozart","Sinfonia Concertante","Classical",1778));
          this.cdCatalogue.put("Mozart", temp);
          this.cdCatalogue.get("Mozart").add(new CD("Mozart","Violin Concertos","Classical",1775));
          this.cdCatalogue.get("Mozart").add(new CD("Mozart","Clarinet Concerto","Classical",1791));
          temp = new ArrayList<CD>();
          temp.add(new CD("Orchestra Baobab","Bamba", "World music", 1981));
          this.cdCatalogue.put("Orchestra Baobab", temp);
          temp = new ArrayList<CD>();
          temp.add(new CD("The Clash", "The Clash", "Punk", 1977));
          this.cdCatalogue.put("The Clash", temp);
          this.cdCatalogue.get("Andy Sheppard").add(new CD("Andy Sheppard", "Andy Sheppard", "Jazz",1998));
          this.cdCatalogue.get("Andy Sheppard").add(new CD("Andy Sheppard","The Birds", "Jazz", 2006));
          temp = new ArrayList<CD>();
          temp.add(new CD("The Sex Pistols","The Great Rock n Roll Swindle", "Punk", 1979));
          this.cdCatalogue.put("The Sex Pistols",temp);
       }
    
    }
    This is what gets displayed....

    Java Code:
    [CD@c3dd7e, CD@10285d8, CD@a14c53]
    [CD@19a19fd]
    [CD@205df9]
    [CD@f9aa66, CD@1224b90, CD@8edb84, CD@edf1de]
    [CD@1a2264c]
    [CD@804a77]
    [CD@98f805]
    [CD@c33893]
    [CD@b749a5, CD@1441b16, CD@4e68fb]
    [CD@1ce508a]
    [CD@9b1ac, CD@6f9f88, CD@52ac68]
    [CD@1b4ee5e]
    [CD@18d9ab8]
    [CD@1a8a9e7]

  2. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    You are printing a CD objects. By default Java will output [className@hashCode] because it doesn't know how to display a CD object as a String.
    You can tell Java how to display CD objects by overriding the toString method in the CD class to return the String that you want to represent the CD object.

  3. #3
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by r035198x View Post
    You are printing a CD objects. By default Java will output [className@hashCode] because it doesn't know how to display a CD object as a String.
    You can tell Java how to display CD objects by overriding the toString method in the CD class to return the String that you want to represent the CD object.
    OK that's ace thanks, I'm now heading in the right direction.
    I have overridden the toString method in the CD class like this...

    Java Code:
    public String toString()
       {
          return this.artist + ", " + this.title + ", " + this.genre + ", " + this.year;
       }
    but I now need to get the details of each CD on separate lines. At the moment I am getting the following display which is grouping CDs by one artist on the same line. The case in point being Andy Sheppard. How do I get around that?

    Java Code:
    [Andy Sheppard, Soft on the Inside, Jazz, 1990, Andy Sheppard, Andy Sheppard, Jazz, 1998, Andy Sheppard, The Birds, Jazz, 2006]
    [Barbara Thompson, Songs from the Centre of the Earth, jazz, 1991]
    [Benjamin Britten, Piano Concerto, Classical, 1938]
    [Bob Dylan, Blood on the Tracks, Other, 1975, Bob Dylan, No Direction Home, Folk/rock, 2005, Bob Dylan, Street Legal, Folk/rock, 1978, Bob Dylan, Blonde on Blonde, Folk/rock, 1966]
    [Dave Brubeck Quarter, Time Out, Jazz, 1959]
    [Gilad Atzmon, Rearranging the 20th Century, Jazz, 2004]
    [Inti-Illimani, Leyenda, World music, 1990]
    [John Adams, Shaker Loops, New music, 1983]
    [Louis Sclavis, Les Violences de Rameau, Jazz, 1996, LouisSclavis, Clarinettes, Jazz, 1984, Louis Sclavis, Phare, Jazz, 2005]
    [Miles Davies, Porgy and Bess, Jazz, 1958]
    [Mozart, Sinfonia Concertante, Classical, 1778, Mozart, Violin Concertos, Classical, 1775, Mozart, Clarinet Concerto, Classical, 1791]
    [Orchestra Baobab, Bamba, World music, 1981]
    [The Clash, The Clash, Punk, 1977]
    [The Sex Pistols, The Great Rock n Roll Swindle, Punk, 1979]

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  5. #5
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    6

    Default

    looks to me like you're printing out a list of items, not the actual items themselves, hence the brackets around them, even the single ones.

  6. #6
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Where's the rest of your program?
    I have included the entire MusicLibrary class in my first post.
    The CD class is as follows. I don't like the fact that I've duplicated code in the toString and printString methods, but one expects to see a String and the other is void.....

    Java Code:
    /**
     * Class CD - Represents the details of a CD to be stored in a catalogue
     * 
     */
    public class CD extends Object
    {
       private String artist; 
       private String title; 
       private String genre; 
       private int year; 
      
    
       public CD(String anArtist, String aTitle, String aGenre, int aYear)
       {
          super();
          this.artist = anArtist;
          this.title = aTitle;
          this.genre = aGenre;
          this.year = aYear;
       }
       
      
       public String getArtist()
       {
          return this.artist;
       }
      
       
       public String getTitle()
       {
          return this.title;
       }
       
       public String getGenre()
       {
          return this.genre;
       }
       
       public int getYear()
       {
          return this.year;
       }
          
       
       /**
        * Displays the details of an instance of class CD
        */
       public void printString()
       {
          System.out.println(this.getArtist() + ", " + this.getTitle() + ", "
                             + this.getGenre() + ", " + this.getYear());
       }
       
       /**
        * Overrides the toString() method
        */
       public String toString()
       {
          return this.artist + ", " + this.title + ", " + this.genre + ", " + this.year;
       }
     }

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  8. #8
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    and the main method? We still don't know how you're running this thing.
    That may be written later, it's a gradual build-up, but at the moment that's all I have

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by trueblue View Post
    That may be written later, it's a gradual build-up, but at the moment that's all I have
    Sorry, but I don't believe that. You're getting output meaning your running a Java program, and you can't be running a Java program without one of your classes having a main method. Please check, find it, and post it. Thanks.

  10. #10
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    1.)You do have a main method somewhere. You need it to run Java programs as applications. I'm not asking you to post it though.
    2.) Every class implicitly inherits from the Object class so you don't have to put the "extends Object" part in your class definition.
    3.) Since you now have the toString method you don't need that printString method.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to change your displayCD method to extract the List<CD> then print the list:

    Java Code:
      public void displayCDs() {
        for (String eachCD : cdCatalogue.keySet()) {
          System.out.println(eachCD);
          List<CD> cdList = cdCatalogue.get(eachCD);
          // now do something with this list to display the individual CDs in the list
        }
      }

  12. #12
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    You need to change your displayCD method to extract the List<CD> then print the list:

    Java Code:
      public void displayCDs() {
        for (String eachCD : cdCatalogue.keySet()) {
          System.out.println(eachCD);
          List<CD> cdList = cdCatalogue.get(eachCD);
          // now do something with this list to display the individual CDs in the list
        }
      }
    Ah yes, it's clear now thank you.
    I need to create a List within the displayCDs method to work with.
    This code works perfectly.
    Oh well I'm off to sort the kids out as the wife is away. Cheers.

    Java Code:
    /**
        * Displays the details of all CDs in an instance of MusicLibrary class
        */
       public void displayCDs() 
       {
          for (String eachCD : cdCatalogue.keySet()) 
          {
             List<CD> cdList = cdCatalogue.get(eachCD);
             for (CD everyCD : cdList)
             {
                System.out.println(everyCD);
             }
          }
      }

  13. #13
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    You need to change your displayCD method to extract the List<CD> then print the list:
    Good Evening.
    Following on from the displayCD method I have now partly created a displayMostRecent(String) method which will display the most recent CD released by the artist String argument no problem, but will not display the relevant warning if the artist is not in the catalogue. Rather it throws an exception (java.lang.IndexOutOfBoundsException: Index: 0, Size: 0) and I can not see why? Could you shed any light on this please? Firstly I know my code may be a bit long winded but it does work, and it can be assumed that the list has already been sorted. Hence the ArtistCDList.get(0) line which just takes the newest CD release which will always be sorted to the index of 0. Many thanks.

    Java Code:
    /**
        * If the artist argument exists in the CD catalogue
        * the details of the artist's most recent CD are
        * displayed. If the artist is not catalogued a
        * warning is displayed.
        */
       public void displayMostRecent(String anArtist)
       {
             List<CD> ArtistCDList = new ArrayList<CD>();
             for (String eachCD : this.cdCatalogue.keySet())
             {
                List<CD> cdList = this.cdCatalogue.get(eachCD);
                for (CD artistCD : cdList) 
                {
                   if (artistCD.getArtist().equals(anArtist))
                   {
                      ArtistCDList.add(artistCD);
                   }
                }
             }
             if (ArtistCDList.get(0).getArtist().equals(anArtist))
             {
                System.out.println(ArtistCDList.get(0));
             }
             else
             {
                System.out.println("There are no titles for this artist");
             }
        }

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    System.out.println is your friend, and heavy use of this while creating and testing your program can be useful as a "poor-man's debugger". For instance add a few println's in your code like so, and what do you see?

    Java Code:
      public void displayMostRecent(String anArtist) {
        List<CD> ArtistCDList = new ArrayList<CD>();
        for (String eachCD : this.cdCatalogue.keySet()) {
          List<CD> cdList = this.cdCatalogue.get(eachCD);
          for (CD artistCD : cdList) {
            if (artistCD.getArtist().equals(anArtist)) {
              ArtistCDList.add(artistCD);
            }
          }
        }
        
        System.out.println("anArtist: " + anArtist);
        System.out.println("\tcdCatalogue.keySet().contains(anArtist): " 
            + cdCatalogue.keySet().contains(anArtist));
        System.out.println("\tArtistCDList.size(): " + ArtistCDList.size());
        
        if (ArtistCDList.get(0).getArtist().equals(anArtist)) {
          System.out.println(ArtistCDList.get(0));
        } else {
          System.out.println("There are no titles for this artist");
        }
      }
    My main method is like so:
    Java Code:
      public static void main(String[] args) {
        MusicLibrary library = new MusicLibrary();
        library.populate();
        //library.displayCDs();
        
        library.displayMostRecent("Bob Dylan");
        library.displayMostRecent("Fred Flinstone");
      }
    hint: my code example uses a Set method that you can also use in your program to simplify this method and prevent this exception from occurring.

  15. #15
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    6

    Default

    you are trying to get the 0th element of the array list, but if it is empty, there are no elements, causing the exception. you only want to get the 0th element if it exists.

  16. #16
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    System.out.println is your friend, and heavy use of this while creating and testing your program can be useful as a "poor-man's debugger". For instance add a few println's in your code like so, and what do you see?

    Java Code:
      public void displayMostRecent(String anArtist) {
        List<CD> ArtistCDList = new ArrayList<CD>();
        for (String eachCD : this.cdCatalogue.keySet()) {
          List<CD> cdList = this.cdCatalogue.get(eachCD);
          for (CD artistCD : cdList) {
            if (artistCD.getArtist().equals(anArtist)) {
              ArtistCDList.add(artistCD);
            }
          }
        }
        
        System.out.println("anArtist: " + anArtist);
        System.out.println("\tcdCatalogue.keySet().contains(anArtist): " 
            + cdCatalogue.keySet().contains(anArtist));
        System.out.println("\tArtistCDList.size(): " + ArtistCDList.size());
        
        if (ArtistCDList.get(0).getArtist().equals(anArtist)) {
          System.out.println(ArtistCDList.get(0));
        } else {
          System.out.println("There are no titles for this artist");
        }
      }
    My main method is like so:
    Java Code:
      public static void main(String[] args) {
        MusicLibrary library = new MusicLibrary();
        library.populate();
        //library.displayCDs();
        
        library.displayMostRecent("Bob Dylan");
        library.displayMostRecent("Fred Flinstone");
      }
    hint: my code example uses a Set method that you can also use in your program to simplify this method and prevent this exception from occurring.
    The thing that struck me about your code was that if the artist was not catalogued and the List ArtistCDList was empty then any boolean comparison between anArtist and a non-existent element in ArtistCDList will throw an exception because it is not a like-for-like comparison?
    However I have changed the code so the boolean comparison checks whether cdCatalogue.keySet().contains(anArtist) because this list is likely to contain something and will return true or false as per the System.out.println insertions.
    I felt unsure about doing this, because I felt I should be referring to the ArtistCDList for a boolean check.
    Rightly or wrongly this does actually work now.
    I hear what you're saying about the main method angle, but it's not in the script as it were and I have to play it by the book.

    Java Code:
    public void displayMostRecent(String anArtist)
       {
             List<CD> ArtistCDList = new ArrayList<CD>();
             for (String eachCD : this.cdCatalogue.keySet())
             {
                List<CD> cdList = this.cdCatalogue.get(eachCD);
                for (CD artistCD : cdList) 
                {
                   if (artistCD.getArtist().equals(anArtist))
                   {
                      ArtistCDList.add(artistCD);
                   }
                }
             }
             if (this.cdCatalogue.keySet().contains(anArtist))
             {
                System.out.println(ArtistCDList.get(0));
             }
             else
             {
                System.out.println("There are no titles for this artist");
             }
        }

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    The thing that struck me about your code was that if the artist was not catalogued and the List ArtistCDList was empty then any boolean comparison between anArtist and a non-existent element in ArtistCDList will throw an exception because it is not a like-for-like comparison?
    No the reason for the exception is as given by emcee above: You can't extract item 0 from an empty ArrayList. For that matter, you can't extract any item from an empty list.

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default

    Just a couple of suggestions here.
    There's no need to iterate over the keySet then use the keys to get the entries. Just get the entry set (entrySet()) and iterate over that. It's much neater, and functionally does the same thing you're doing.

    So this:
    Java Code:
             for (String eachCD : this.cdCatalogue.keySet())
             {
                List<CD> cdList = this.cdCatalogue.get(eachCD);
    ...
    becomes this:
    Java Code:
             for (List<CD> cdList : this.cdCatalogue.entrySet())
             {
    ...
    Second, isn't the key to your map the artist?
    So why not do this (note, variable names should start with a lower case):
    Java Code:
    List<CD> artistsCD = cdCatalogue.get(anArtist);
    ?

  19. #19
    trueblue is offline Member
    Join Date
    Mar 2009
    Posts
    57
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    No the reason for the exception is as given by emcee above: You can't extract item 0 from an empty ArrayList. For that matter, you can't extract any item from an empty list.
    I also tried a boolean check on
    Java Code:
    ArtistCDList.isEmpty()
    and I thought this would work but it still threw an exception?

  20. #20
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    So you mean the list is not empty but position 0 has nothing? Did you put anything at position 0 at all?

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 8
    Last Post: 12-29-2008, 07:12 AM
  2. Capture elements from an List in a different package
    By blevault in forum New To Java
    Replies: 5
    Last Post: 11-27-2008, 09:14 AM
  3. trying to set() values of in list of arraylist
    By alvations in forum New To Java
    Replies: 15
    Last Post: 10-13-2008, 09:35 PM
  4. Getting values of an Option List
    By mutuah in forum Advanced Java
    Replies: 0
    Last Post: 08-07-2007, 03:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •