1

I want to know if have two arrays testSet and testSet2 of class test1 in method problem() testSet is initialized to 1 and testSet2 is initialized to 0 and after equalizing the testSet2 with testSet the testSet2 lenght become same as of testSet which is fine but in method problem1() testSet is initialized to 1 and testSet2 is initialized to 0 and after equalizing in method equalize() the testSet2 with testSet the testSet2 lenght become is still 0. why?

public class test1
{
    // C
    public test1(int _data)
    {
        data = _data;
    }

    // Field
    public int data;
}

// reference equalize method
public void equalize(test1[] a,test1[] b)
{
    a = b;
}

public test1[] testSet,testSet2; // arrays

// called from main method access
public void Problem()
{    
    // initializing array
    testSet = new test1[1];
    testSet2 = new test1[0];

    testSet [0] = new test1 (11);
    testSet2 = testSet;  

    // testSet2.length = 1 which is fine
}

// called from main method access
public void Problem1()
{  
    testSet = new test1[1];
    testSet2 = new test1[0];

    testSet [0] = new test1 (11);
    equalize (testSet2,testSet);

    // want to know why this is happening ?
    // testSet2.length = 0 
    // in problem() length = 1 but here is 0 why?
}
parminder
  • 31
  • 4
  • 3
    Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – default locale Feb 09 '17 at 10:22

1 Answers1

0

the reason why the length of testSet2 = 0 was because the method equalize() only use them inside. methods() used the parameters only on their behalf.

if you want to change the length of testSet2. initiate it on the

  public TestClass(int _data)
   {
        data = _data;
    testSet2 = new TestClass[0];
}

 and when you want to change it's length try this

 public void Problem1()
{  
testSet = new TestClass[1];
testSet [0] = new TestClass (11);
 equalize (testSet);   

System.out.println(testSet2.length);
System.out.println(testSet.length);



 }

  public void equalize(TestClass[] b)
{
testSet2 = b;
 }
Mr.Aw
  • 216
  • 3
  • 16
  • public void equalize(test[] a,test[] b){ b[0].data = 1000} then how b.data[0] sets in other function even if it was locally in equalize function as you said? – parminder Feb 10 '17 at 05:05