• Post Reply Bookmark Topic Watch Topic
  • New Topic

Where to declare a list in code  RSS feed

 
Maksim Li
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone!

I am having hard time understanding where to declare a list (like ArrayList or LinkedList)...

For example, if I want to create an ArrayList of song. Can I declare this ArrayList directly within the Song class itself? or should I declare it outside the Song class? If I could declare the ArrayList within the Song class, do I need to add "static" access modifier in the declaration of this ArrayList? Will this ArrayList still exist if I only declare it within a method of Song class?

Thanks very much!
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 36656
475
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While you could declare a static list in the Song class, this is less common. You are more likely to create the list in the code that calls Song.

Declaring a list inside a method is a local variable and not accessible elsewhere (unless you return it and store it somewhere)
 
Maksim Li
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:While you could declare a static list in the Song class, this is less common. You are more likely to create the list in the code that calls Song.

Declaring a list inside a method is a local variable and not accessible elsewhere (unless you return it and store it somewhere)


Thanks very much!
 
Sami Kassoum
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can easily use ArrayList like this  :

 
Liutauras Vilda
Marshal
Posts: 3961
214
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sami Kassoum wrote:You can easily use

Need to try harder rather than easier. That code wouldn't compile even introducing missing parts. Apart from that, it has very bad indentation and formatting and other errors.

Maybe next time
 
Sami Kassoum
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:
Sami Kassoum wrote:You can easily use

Need to try harder rather than easier. That code wouldn't compile even introducing missing parts. Apart from that, it has very bad indentation and formatting and other errors.

Maybe next time


you are absoulutly right,I abologize for the mistakes,I  actually wrote the code from my smartphone without the help of netbeans
her is a better runnable version.



run:
Song name: smile
Song name: Feel
Song name: Dance with me
BUILD SUCCESSFUL (total time: 0 seconds)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!