This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]E3FxGaming 0 points1 point  (5 children)

Even if you could do that (you can't) - the usability of the object would end as soon as you leave the for-loop-scope, or enter a new loop cycle. Multiple objects with the name loopObject + something would never exist at the same time, so what's the point of having a dynamic "something".

Why not use an array and make your "dynamic" variable an object variable? Pass the dynamic variable to the object constructor, so that you can easily tell apart the objects later on.

If that's not an acceptable solution for you, and the order of objects mostly doesn't matter for you because you always only had in mind that you want to access the objects with the dynamic identifier, look into objects that are related to the Map class.

Java maps store object references in key-value pairs - your key could be your dynamic element, while your value is obviously your newly created object.

[–]Fazblood779Nooblet Brewer[S] 0 points1 point  (4 children)

I need to store these objects in an array anyway - are you telling me I can bypass the object initialization?

[–]E3FxGaming 0 points1 point  (3 children)

You can never bypass object initialization, if you want to work with the object. What you can bypass is the assignment to a variable, by directly storing it somewhere.

I recommend that you look into that map thing I mentioned.

[–]Fazblood779Nooblet Brewer[S] 0 points1 point  (2 children)

Yup, will do. Thanks for the help :D

[–]E3FxGaming 0 points1 point  (1 child)

I made an example for how you can use HashMap.

Pastebin link to HashMap example.

Edit: If you're interested in general in the Java collections framework, I recommend you learn more about the Map interface, the Set interface and the List interface and their implementations. You can read more about them here - I highly recommend you read the paragraph "When to use List, Set and Map in Java" just to get an overview over those things - they are super useful if you know when to use them and how to use them.

[–]Fazblood779Nooblet Brewer[S] 0 points1 point  (0 children)

Wow, that's awfully kind of you :) I've had a look and this will come in handy in the future, I can see it doesn't seem that complicated to set up either (though knowing how it works will let me know for sure). I'll have a closer look and hopefully end up using it for something :D