hello everyone...
I'm new in java and is currently studying about collections...
I'm trying to make my own collection package so that I would understand more about the functions of the collection classes and interfaces....
I'm currently making my own HashSet class and I have a problem about preventing duplicates...here the code...
my problem is that my custom HashSet class doesn't let null values in the object[]...does anyone has a suggestion on what I should do?...tnx...[/B]Code:// The IMySet interface has the following abstract method(s) // public void clear(); // public void remove(Object obj); // and implements the IMyCollection interface and here are its abstract method(s) // public void add(Object obj) // public void add(IMyCollection collection) // here's my code for my custom HashSet class[/B] public class CMyHashSet implements IMySet { // attribute(s) private Object[] object; private boolean[] isShown; private int counter; // constructor(s) public CMyHashSet() { object = new Object[16]; isShown = new boolean[16]; } // close CMyHashSet() // implemented method(s) public void add(Object obj) { if ( addObject(obj) ) { object[counter] = obj; isShown[counter] = true; counter++; } // close if (...) } // close add(Object) public void add(IMyCollection collection) { if ( addObject(collection) ) { object[counter] = collection; isShown[counter] = true; counter++; } // close if (...) } // close add(Collection) public void remove(Object obj) { // haven't done yet } // close remove(Object) public void clear() { object = new Object[16]; isShown = new boolean[16]; counter = 0; } // close clear() public String toString() { StringBuffer my_string = new StringBuffer(); my_string.append( '<' ); for (int i = 0; i < object.length; i++) { if ( isShown[i] ) { my_string.append( object[i] ); if ( i < countIsShown() - 1 ) { my_string.append( ", " ); } // close if (...) } // close if (...) } // close for (...) my_string.append( '>' ); return ( my_string.toString() ); } // close toString() // other method(s) // count how many true values isShown[] has private int countIsShown() { int numOfTrueValue = 0; for (int i = 0; i < isShown.length; i++) { if ( isShown[i] ) { numOfTrueValue++; } // close if (...) } // close for (...) return ( numOfTrueValue ); } // close countIsShown() // checks if an Object has duplicates with // one of the Objects of the object[] private boolean addObject(Object obj) { boolean isAdded = true; for (int i = 0; i < object.length; i++) { if ( object[i] != null && object[i].hashCode() == obj.hashCode() ) { isAdded = false; break; } // close if (...) } // close for (...) return ( isAdded ); } // close addObject(Object) } // close CMyHashSet class


Reply With Quote


Bookmarks