public class Set{ private T arrayElement[]; int size =0; public Set(){ this.arrayElement = null; } public Set(T[] element){ arrayElement = element;// array can be assigned size = arrayElement.length; } /** *add element to set. A check is made to identify whether element is present or not. *If not the element can be inserted. * @param element */ public void addElement(T element){ if(!contains(element)){ if(size == arrayElement.length){ incrementArray(); } arrayElement[size++] = element; } } /** * to check is element is present or not. * @param elem * @return boolean */ O(n) public boolean contains(T elem){ if (elem == null) { for (int i = 0; i < size; i++) if (arrayElement[i]==null) return true; } else { for (int i = 0; i < size; i++) if (elem.equals(arrayElement[i])) return true; } return false; } /** * this function is used to increment the size of an array * */ private void incrementArray(){ T[] temparray = arrayElement; int tempsize=size+5; arrayElement =(T[]) new Object[tempsize]; System.arraycopy(temparray, 0, arrayElement, 0, size); } public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) http://www.java-samples.com/showtutorial.php?tutorialid=641 The difference is that Arrays.copyOf does not only copy elements, it also creates a new array.System.arrayCopy copies into an existing array. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0] [1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3] http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/ /** * return the size of set. * @return int */ public int size(){ if(arrayElement != null){ return arrayElement.length; }else return 0; } public void clear(){ arrayElement = null; } public String toString(){ if(arrayElement == null || arrayElement.length ==0 ){ return“[EMPTY]”; }else{ String toStr=”[“; for(int i=0;i
Sunday, September 13, 2015
[Data Structure] Set Implementation
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment