0

I want to understand what is clone() method's benifit and when i should use it, why sometimes when i give the value of a variable to another variable the other variable links to the first variable, i mean when you make change to one of them the other's value automaticlly changes to this value which you changes although some times it doesn't happens. OK now i show some examples:-

  • When initialising a RectF variable in Android Java language into another RectF variable it happens, (e.g.) :-

    static RectF var1;
    
    //initialise it
    
    static void someVoid(){
        RectF var2 = var1;
        var2.set(...);
        //now when i changed var2 also the var1 changed
    } 
    
  • but when initialising an Integer variable to another integer variable it won't happens, (e.g.) :-

    static int azhy = 1000;
    
    static void someVoid(){
        int hello = azhy;
        hello++;
        //now when i change the hello variable azhy variable stays constantly
    }
    

i searched somewhere but i didn't found a result so if you can give me some description i will thankyou.

Azhy
  • 704
  • 3
  • 16

2 Answers2

1

See the answer here for some useful background on the difference between Objects and primitives. int is a primitive type, while RectF is an object.

You can think of a primitive type assignment operation (int hello = azhy;) as copying the value from azhy to hello, but they do not refer to the same object (so modifying hello does not modify azhy.

On the other hand, RectF is an Object, so calling RectF var2 = var1; means that both var1 and var2 now refer to the same object. As such calling a method on var2 modifies var1.

Note, int is a primitive type, but Integer (which you refer to in your question) is an object.

Tyler V
  • 9,694
  • 3
  • 26
  • 52
1

In your first example you're using an object, so when you do this:

RectF var2 = var1;

You're actually make var2 point to the same memory of the computer and when you change the value from one object it also changes it to the other because it's the same memory space, but with a different name.

In your second example you're using primitive variables, so when you do:

int hello = azhy;

You're just copying the value in a new memory space of your computer.

If you want to copy an object without making them be the same, you would have to make a new instance of that object and only copy the values. Use this as a reference

Pietro Nadalini
  • 1,722
  • 3
  • 13
  • 32