Search code examples
parametersanylogic

Copy entire javaclass or its parameters without inheritance in Anylogic


I'm trying to model a factory with production orders in Anylogic. Unfortunately, I'm a beginner in java ...

I created two new JavaClasses for my model. A "bill of material"(stueckliste) and "entry of bill of material"(stuecklisteneintrag). The bill of material has a linked list:

String name;
LinkedList<Stuecklisteneintrag>stuecklisteneintrag = new LinkedList<Stuecklisteneintrag>();

The "entry of bill of material"(stuecklisteneintrag) class has a lot of parameters.

If i want to create a

new Stueckliste();

with new entries:

Stuecklisteneintrag stkE = new Stuecklisteneintrag()

based on existing entries:

stkE = stueckliste.stuecklisteneintrag.get(test);

How do I copy an entire "entry" without the inheritance to the existing entry? Because if i change the parameters, both parameters in the old and new entry will change ...

stkE = stueckliste.stuecklisteneintrag.get(test);
a.fertigungsstueckliste.stuecklisteneintrag.add(stkE);
a.fertigungsstueckliste.stuecklisteneintrag.getFirst().name= "Test";
traceln(a.fertigungsstueckliste.stuecklisteneintrag.getFirst().name);
traceln(stueckliste.stuecklisteneintrag.getFirst().name);

Both names will be "test". Or if i delete entries in the new bill of material, entrys in the old one are deleted as well ...


Solution

  • You need to do a "deep copy" of your data. Create a new constructor for Stuecklisteneintrag as:

    public Stuecklisteneintrag(Stuecklisteneintrag oldEintrag) {
        this.field1 = oldEintrag.field1;
        ... // add all fields here
    }
    

    This will create a new Stuecklisteneintrag instance that takes from the oldEintrag instance but they are now "de-coupled" :)

    NOTE: You can only do this for primitive data types (int, double, boolean) as well as for Strings. If you have fields that are other Java classes, they need deep copies as well!