1

Why does this code change the value of set1 in the last print statement, I was under the impression that in Java arguments were passed by value?

Am I missing something?

import java.util.Set;
import java.util.TreeSet;


   public class Testing {
      public static void main(String args[]) {

       Set<String> set1 = new TreeSet<String>() ;
       set1.add("A") ;
       set1.add("B") ;
       set1.add("C") ;
       set1.add("D") ;
       set1.add("F") ;
       set1.add("G") ;
       System.out.println("set1, the tree set: " + set1) ;

       Set<String> set2 = new TreeSet<String>() ;
       set2.add("B") ;
       set2.add("D") ;
       set2.add("E") ;
       set2.add("F") ;
       set2.add("G") ;
       System.out.println("set2, the tree set: " + set2) ;

       Set set3 = difference(set1, set2);

       System.out.println("Difference: " + set1 + " - " + set2 
                    + " = " + set3) ;



    }
    public static Set<String> difference(Set<String> x, Set<String> y)
    {

        x.removeAll(y);

        return x;
  }}
Jurgen
  • 337
  • 3
  • 10

2 Answers2

1

Java is pass-by-value, but the value it is passing in this case is a reference to a Set, so it can modify the original object.

nbarriga
  • 36
  • 4
0

You confused with the term pass by value. pass by value in the sense reference passed as value. Reference value passed, and the set gets effected.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307