0

I am initalizing several objects of the same type that have a common field:

public class Example { private static objectCounter = 1; public Example () { objectCounter++; } } 

Since these objects are created with a for loop like this

for (int i = 0; i<5; i++) { Example e = new Example(); } 

they are not referenced.

Is there a way to get a specific object based on objectCounter value ?

Something like

//get the Example object with objectCounter==2 get(2); 

Thank you

2
  • I think you misunderstand what a static field is. A static field means all your instances share one single value. So All your Example objects will have the same value for objectCounter (referenced by Example.objectCounter). You need to assign your counter to a non static variable if you want to distinguish your objects by that value. Commented Feb 10, 2021 at 12:07
  • Also you should be aware that the way you create your objects as local variables in a for loop, that these objects will be deleted by the garbage collector at some point because there is no reference with which you could address them once the loop is done. So after your loop is done running and the garbage collector kicks in there are no objects that you could even get. Commented Feb 10, 2021 at 12:13

2 Answers 2

1

My suggestion will be saving into array:

Example store[] = new Example[5] for (int i = 0; i<5; i++) { store[i] = new Example(); } 

And then , search for the specific object.

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

Comments

1

As stated in the comments, a static value will persist through all instances of your class.

If you want your Example to "know" it's identity, pass it in when you construct it:

Example:

public class Example { private int id; public Example (int val) { this.id = val; } // Getters/setters } 

Probably also want to add your objects to a list to access them later, so before your for-loop:

List<Example> examples = new ArrayList()<Example>; 

And create them like this:

for (int i = 0; i<5; i++) { Example e = new Example(i); examples.add(e); } 

Comments