About new objects

Issue

I have a base object in a game that is used for stats. I copy the object each time I start a battle for the 40 sum units on the battle map.

I then modify the stats object for each unit. I of course do not want to pass by reference. The base stats object is filled with about 50 primitives. So I have created a constructor class of the object and have tediously gone and done copied each primitive. This seemed the safest way from what I found googling.

Example Code

class Stats{
int x;
int y;
int b;

public Stats(Stats stats)
{
this.x = stats.x;
this.y = stats.y;
this.b = stats.b;
}
}

Stats currentUnit = new Stats (currentUnitBaseStats);

-questions-

This is extremely frustrating and messy. Is it worth my time to look into implementing the built in cloning function?

If my stats class eventually contains other objects, will all objects contained within it also need to implement the cloning function?

Is there an easier way??

Side questions: on Android holding 40 separate classes of 100~ primitives is still pretty low on RAM consumption right?
Thanks and I love you guys 🙂

Solution

If you have so many primitives (50) why don”t you use a HashMap ? :

    public static void main (String[] args)
{
    HashMap<String, Integer> stats = new HashMap<String,Integer>();
    stats.put("x",3);
    stats.put("y",4);
    stats.put("z",5);
    stats.put("b",9);
    HashMap<String, Integer> statsCopy = new HashMap<String,Integer>();

    statsCopy.putAll(stats);//this will copy all the values from the base object
}

Answered By – Tourki

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.