• Post Reply Bookmark Topic Watch Topic
  • New Topic

printing instance variables of an object in an arraylist  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys

i have two classes





but when i print out the object (which i know you cant do) i get a dsfsdf@35353 type thing
how can i print out the team
manu 2 red 300000000

etc from my arraylist

it seems i cant get to the instance variables in my object thats in the arraylist

thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does your Team class override toString()? If not, it inherits the toString() from Object which does not do what you want to do.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can actually print objects. All you have to do is override the toString() method on your Team class, so it displays in a way that you want it to.

There are some other issues with your code:

  • You shouldn't use methods to do what a constructor should do. Instead of a method createTeam(), give Team a constructor.
  • Your constructor should perform parameter checking. Is null a valid value for a team name?
  • Use clear variable names. tn is not a clear name. For constructors and setters, you can use the same name as your fields, and then refer to the fields using the this keyword.
  • You're using raw generic types, and you're not using interfaces. Instead of:
  • Do:
     
    Sami Kassoum
    Ranch Hand
    Posts: 39
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    line 19 in class Match, theLeague.get(0) will return you an Object that you have to typecast it to Team object, and System.out.println don't know how to deal with it ,it will never print out its inner fields.
    use the following :-
    Team t = (Team) theLeague.get(0);
    System.out.println(t.teamName);
    .
    .
    .
    .
     
    Bear Bibeault
    Author and ninkuma
    Marshal
    Posts: 66307
    152
    IntelliJ IDE Java jQuery Mac Mac OS X
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Sami Kassoum wrote:System.out.println don't know how to deal with it ,it will never print out its inner fields.

    Unless, as previously pointed out, the toString() method is overridden. So, not "never".
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!