0

I have this piece of code:

    Graph g = new Graph();

    doCoverOperation(g) 

where in doCoverOperation(g, subset) I tend to do some operation with g but I do not want to have any changes on my g. Since I came to understand Java is a pass by reference, I know this is how it is supposed to work, but is there a way I can pass a clone on doCoverOperation? Like, I do some operation with g on doCoverOperation but my g above does not change?

Any ideas on this approach? Thank you further!

  • 4
    "Since I came to understand Java is a pass by reference" - no, references are passed by value. See https://stackoverflow.com/questions/40480. But if you want to create a clone, you'll need to write the code to clone the graph. That's sometimes hard, and sometimes easy, depending on the data structures involved. – Jon Skeet Aug 22 '19 at 21:06
  • 1
    "*Since I came to understand Java is a pass by reference...*" - [Java is pass-by-value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value), always. If you want this to happen automatic cloning, you most probably have to wait for [Project Valhalla's value types](https://openjdk.java.net/jeps/169). – Turing85 Aug 22 '19 at 21:06
  • Java is only pass by value, but since references are literally that, *references*, objects in Java have pass by reference semantics. It's a subtle point but something to keep in mind. – markspace Aug 22 '19 at 21:08
  • 1
    Search internet for "Java deep clone library", you'll find several , you can start with stackoverflow question: https://stackoverflow.com/questions/665860/deep-clone-utility-recommendation – Rostislav Matl Aug 22 '19 at 21:12
  • I'd urge you to think carefully, does the `doCoverOperation()` method really need to be mutating its input? In general, methods that mutate their input data structure are less maintainable and more error prone than ones that don't – MyStackRunnethOver Aug 22 '19 at 21:26

1 Answers1

0

If you implemented the Graph class yourself, then your class can implement the Cloneable interface like this:

public class Graph implements Cloneable {

    // Your methods and properties go here
    ...

    @Override
    public Object clone()throws CloneNotSupportedException{
        return super.clone();
    }
}

Then you can use the clone method like this:

Graph g1=g.clone();
MyStackRunnethOver
  • 4,872
  • 2
  • 28
  • 42
Mahbube
  • 13
  • 1
  • 8