Followers 0

Help with ArrayList Java

7 posts in this topic

I am currently working on a text based game using swing. In it, I have the user create a game world (essentially just a new folder name and then some serialized files in it). I a trying to make a way to import what data they want from one world to another. My problems is, instead of making a new popup for each object, I want to create just one and pass a string to it in order to get what serialized object for the popup to get. I have tried to turn the string into a class name via Class className = Class.forName("com.package.class") method, however, when I try to input that into ArrayList<className> arrayList, it tells me className cannot be resolved to a type. Is there anyway i can achieve this? Or am I going to have to make a popup for each object I want to have imported?

0

Share on other sites

Thank you megadan, I now have it reading the ArrayList using Class<?>. Now my problem is adding elements to an ArrayList<Class> from ArrayList<Class<?>>.

Example:

ArrayList<Moves> moves;
ArrayList<Class<?>> importedMoves;

for (int x = 0; x < importedMoves.size(); x++){


Is there a way around this?

0

Share on other sites

Thank you megadan, I now have it reading the ArrayList using Class<?>. Now my problem is adding elements to an ArrayList<Class> from ArrayList<Class<?>>.

Example:

ArrayList<Moves> moves;
ArrayList<Class<?>> importedMoves;

for (int x = 0; x < importedMoves.size(); x++){


Is there a way around this?

Just remove the generics all together, it seems like you don't want type checking. This can cause problems in the future though (you'll need to type cast), and it'll also make the code harder to understand.

Edited by patrrr
1

Share on other sites

This code should theoretically work, however I haven't tested it ( getting ready for work as I type this message ) .

ArrayList <Object> Something = new ArrayList <Object>() ;


"Object" is a generic that should be able to hold any kind of object .

Edited by Shippou
1

Share on other sites

This code should theoretically work, however I haven't tested it ( getting ready for work as I type this message ) .

ArrayList <Object> Something = new ArrayList <Object>() ;


"Object" is a generic that should be able to hold any kind of Object .

Which is what ArrayList without the generics will result in, afaik

Edited by patrrr
1

Share on other sites

Thanks guys. The combination of using ArrayList<Object> and then casting the Object to a specific class type worked. You guys saved me several hours of coding. I can't thank you guys enough.

0

Create an account

Register a new account