About new objects

54 views Asked by At

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 :)

2

There are 2 answers

2
Tourki On BEST ANSWER

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
}
1
Sean McCullough On

This is the best way to implement your Stats class. It may seem frustrating and messy, but functionally, that class is very simple.

If the stat values never chance, you could consider making Stats a static class. Then, you never need to copy it. For example:

static class Stats
{
    private int x = 10;
    private int y = 12;
    private int b = 13;
    ...
    public int getX()
    {
        return x;
    }
    public int getY()
    {
        return y;
    }
    public int getB()
    {
        return b;
    }
}

To get these values, you would call Stats.getX(), and would never have to instantiate the Stats class. The downside is that Stats would be the same for all objects referencing it.

If you need independent stat values, you should use your current implementation.

If the starting values are the same for all stat Objects, you could create an additional constructor to set those values.

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

    public Stats()
    {
        this.x = 10;
        this.y = 11;
        this.b = 12;
    }
}

To answer your second question, 40 Objects with 100 primitives would take a maximum of 32,000 bytes, or ~32KB, assuming they were all doubles. On modern hardware, that shouldn't be a problem, however if you can reuse your data, I encourage you to do so.