Cloning Java objects

The main class has:
1) class class1, which has a two-dimensional array and a few more variables
2) function func (class1 cl) which accepts an object of the class but returns a different data type (float), while inside the function body manipulations are performed with a two-dimensional array of the class to get the answer

So, the problem is that if I create an instance of a class, call a function and pass it there, then after that the original array of the object changes (What I naturally don't need to) I found a solution in the form of the clone () method, but the hash code of the objects became different, but the hash code of the fields inside the clone of the object is the same, and accordingly, when changing the array of one object, the array of the other changes

Please tell me how to solve this problem?

Author: BogdanBida, 2017-11-02

2 answers

Make class1 serializable (add implements Serializable to its definition).

Saving the class object to a byte stream: ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream ous = new ObjectOutputStream(baos); ous.writeObject(new class1()); ous.close();

Now in func you can pass (class1)new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject()

Thus, the object of the class is saved in the stream from which it is restored independent clone.

 1
Author: pinguin, 2017-11-03 13:04:31

In order for the clone method to clone the object's fields, it must be redefined in the class itself. By default, it operates only with primitive types and pointers

But you just need to copy the array. To do this, there is a method Arrays.copyOf() or simply call clone for the array

Here are the different methods for getting a copy of the array https://stackoverflow.com/a/36513254/5376639

 3
Author: Anton Shchyrov, 2017-11-02 21:45:03