• Post Reply Bookmark Topic Watch Topic
  • New Topic

get all the names in a list for objects  RSS feed

 
Anton Sigurdsson
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry for bed english.

is ther any way to make this happen?

i like to get all the names in a list from all my objegts.
i tray to use +counter

pepole pepoleObjegt = new pepole();
-------- this was cut out--------
pepole pepoleObjegt200 = new pepole();

int counter = 0;
while(counter < 200) {
System.out.println(pepoleObjegt+counter.getName()):
counter++;
}

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you can't build up variable names at runtime like that. It sounds like what you need is an array or a List or a Map.

An array is useful and simple if you know how many elements there will be at the time you create the array, and if you want to access them by index (position).

A List is useful if you want it to grow as new elements come in, and it is a higher-level abstraction than an array.

A Map is useful if you want to access elements by a key (a "name") that is something other than a numerical counting index.
 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch


i like to get all the names in a list from all my objegts.


where is this name defined in Object ?
If I assume name is defined in People object



Now you can create 200 objects with different names



Now you have a List of people Objects. Now you can list of names in another list.


After this loop execution, you shall get List of Names.


~ abhay

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anton Sigurdsson wrote:i like to get all the names in a list from all my objegts.

Objects don't have names. Variables have names. Note that a variable is not the same as an object; a variable is a reference to an object. You can have multiple variables that refer to the same object.

Anton Sigurdsson wrote:
pepole pepoleObjegt = new pepole();
-------- this was cut out--------
pepole pepoleObjegt200 = new pepole();

You're not the first person who is trying to do something like this (I've seen the same question before on the forums). Instead of creating 200 separate variables in your program, use an array to store all those objects, or a collection such as an ArrayList.
 
Anton Sigurdsson
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the fast response to my question, and the Arrays links.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!