Results 1 to 1 of 1
 05162013, 09:22 PM #1Member
 Join Date
 Oct 2010
 Posts
 51
 Rep Power
 0
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:
 add  adds an item but leaves the set unchanged if the item is already a member of the set
 remove  removes an item but leaves the set unchanged if the item is not a member of the set
 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.
Java Code:class RangeSet { private boolean[] arr; public RangeSet(int n) { arr = new boolean[n]; } public boolean add(int n) { if(arr[n1]) return false; arr[n1]=true; return true; } public boolean remove(int n) { if(!arr[n1]) return false; arr[n1]=false; return true; } public boolean contains(int n) { return arr[n1]; } }
For add method:
Java Code:if(arr[n1]) return false; arr[n1]=true; return true;
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 forloop etc.Last edited by whateverme; 05162013 at 09:25 PM.
Similar Threads

adding integers of an array
By Lene90 in forum New To JavaReplies: 9Last Post: 05082011, 12:12 PM 
how do you add up integers in an array?
By shazakala in forum New To JavaReplies: 7Last Post: 04192011, 10:32 AM 
Printing repeating integers in a given array?
By baumboards in forum New To JavaReplies: 7Last Post: 01242011, 08:08 PM 
Error if array contains duplicate integers
By lithium002 in forum New To JavaReplies: 4Last Post: 12052009, 09:58 AM 
Finding Strings, booleans and Integers
By Pez in forum SWT / JFaceReplies: 1Last Post: 07192009, 02:24 PM
Bookmarks