# array of booleans to represent a set of integers

• 05-16-2013, 09:22 PM
whateverme
array of booleans to represent a set of integers
Hey I was wondering if anyone could explain this further. This is not an assignment, it's just a solution to one of my tests I had. I've been trying to understand it but I'm not sure..

Basically the question for the answer given is:

Write a class in Java called RangeSet which uses the data structure of an array of booleans to represent a set of integers using 3 methods:
1. add - adds an item but leaves the set unchanged if the item is already a member of the set

1. remove - removes an item but leaves the set unchanged if the item is not a member of the set

1. contains - returns a boolean value which says whether an item is a member of the set

there should be one constructor for the class which takes an integer n and gives an object representing a set that can hold integers in the range 1 to n inclusive. The constructor should give an empty set. The set should be destructive. The methods should return true if the set was changed by operation and false if it was not.

Basically, here it is, a Set of integers limited to a range 1 to n, implemented by an array of booleans The methods add and remove return a boolean saying whether the set has been changed by their call, it is assumed all arguments to the methods add, remove and contains will be within the 1 to n range so there is no special code to deal with the cases when the argument is not in range.

Code:

```class RangeSet {     private boolean[] arr;     public RangeSet(int n)     {           arr = new boolean[n];     }     public boolean add(int n)     {         if(arr[n-1]) return false;         arr[n-1]=true;         return true;     }     public boolean remove(int n)     {         if(!arr[n-1]) return false;         arr[n-1]=false;         return true;     }     public boolean contains(int n)     {           return arr[n-1];     } }```
What I don't get is that:
Code:

```if(arr[n-1]) return false;         arr[n-1]=true;         return true;```
I get n-1 is the length of the array, but why false?
then set it to true... I can't get my head around this?
So if I wanted to add int of value 4... why is it we are checking arr[3], why not going through the elements first then if the element is not there add into the array using for-loop etc.