-1

I have an ArrayList of HashSets named "set" and to operate on the individual HashSets I am copying the Set's value to a temporary HashSet "temp" but when I make changes to temp by the command "temp.retainAll(set.get(i))" it changes the original Set... please help me. the code is given below:

public class newques { 
public boolean ValidCorner(int matrix[][]) 
{ 
    // Your code goes here
    boolean result = false;
    int r = matrix.length;
    int c = matrix[0].length;
    ArrayList<HashSet<Integer>> set = new ArrayList<>();
    for (int i = 0; i < r; i++) {
        HashSet<Integer> temp = new HashSet<>();
        for (int j = 0; j < c; j++) {
            if (matrix[i][j]==1) {
                temp.add(j);
            }
        }
        set.add(temp);
    }

    System.out.println(set);
    System.out.println("Size of set is: " + set.size());

    for (int i = 0; i < set.size(); i++) {
        for (int j = i+1; j < set.size(); j++) {
            HashSet<Integer> temp = set.get(i);
            System.out.println(temp);
            System.out.println(set.get(j));
            temp.retainAll(set.get(j));
            System.out.println(set.get(i));
            System.out.println("Temp set is: " + temp);
            System.out.println();
            if (temp.size() % 2 == 0 && temp.size() != 0) {
                result = true;
                break;
            }
        }
    }
    return result;
}

}

1 Answers1

0

This instruction HashSet<Integer> temp = set.get(i); makes you are accessing the same collection that is "inside" set in position i. That's why it's modifying.

You have to create a new collection

Set<Integer> temp = new HashSet<>(set.get(i));

This way both will point to different collections.

Maybe the following will help in a deeper understanding of this: Duplicating objects in Java

pringi
  • 3,987
  • 5
  • 35
  • 45
  • Thanks for taking time to review the question and answering but isn't java call by reference and never call by reference? So even if I initialize temp like "HashSet temp = set.get(i);" shouldn't the set.get(i) be passed as a different collection? – Nobil Gautam Feb 16 '22 at 12:41
  • For example if I declare, int x = 5; int y = x; y++; then the value of y will become 6 but the value of x will still be unchanged. Please bear with me and kindly tell me where am I wrong. – Nobil Gautam Feb 16 '22 at 12:44
  • Primitives are not objects. – pringi Feb 16 '22 at 12:50