Vickie
Vickie

Reputation: 99

Java sets- remove all

I have a method that takes in an array of strings. My problem is with the output: From the line to print setOfArray I get the following output which is correct for array

(buy,pay,sell): [sell, pay] [sell]
[] [buy, sell] [buy] [buy, pay]

However this doesn't transfer into mapOfPermissions.

My output is:

{buy:pay:sell:=[buy, sell, pay],
pay:=[buy, sell, pay], pay:sell:=[buy, sell, pay], buy:=[buy, sell,
pay] . . . . }

Any ideas how I could fix this?

public Map build (String[] array){   
    setOfArray = new HashSet<String>();

    for (String a : array ){
        setOfArray.add(a);
    }

    Arrays.sort(array);
    int n = array.length; 
    String current = "";

    int i = 0;

    while ( i<n) {  

        for (int j = i ; j<n ; j++){    

            current = current + (array[j] + ":");   
            woSeed = new HashSet<String>();
            StringTokenizer stringtokenizer = new StringTokenizer(current, ":");
            while (stringtokenizer.hasMoreElements()) {

                woSeed.add(stringtokenizer.nextToken());

            }

            setOfArray.removeAll(woSeed);

            System.out.println(setOfArray);
            mapOfPermissions.put(current,setOfArray);

            for (String a : array ){

                setOfArray.add(a);
            }       
        }   
        current = "";
        i++;            
    }
    return mapOfPermissions;
}

thanks

Upvotes: 0

Views: 137

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30839

The problem is with the below line:

mapOfPermissions.put(current,setOfArray);

Basically, we are putting the values in the map, however, we still have the reference (i.e. setOfArray) and hence, when we add/remove elements using that reference, the value in the map gets changed. The solution is to use the below line instead:

mapOfPermissions.put(current,new HashSet<String>(setOfArray));

This puts a copy of the set into map and hence, further changes in that set don't affect the map value.

Upvotes: 1

Related Questions