import java.util.*; public class SeparateChaining<T> { private static final int DEFAULT_TABLE_SIZE = 101; private List<T>[] theLists; private int currentSize; public SeparateChaining() { this(DEFAULT_TABLE_SIZE); } public SeparateChaining(int size) { theLists = new LinkedList[size]; for(int i=0; i<theLists.length; i++) theLists[i] = new LinkedList<>(); } public void insert(T element) { List<T> whichList = theLists[myhash(element)]; if(!whichList.contains(element)) { whichList.add(element); currentSize++; } } public void remove(T element) { List<T> whichList = theLists[myhash(element)]; if(whichList.contains(element)) { whichList.remove(element); currentSize--; } } public boolean contains(T element) { List<T> whichList = theLists[myhash(element)]; return whichList.contains(element); } public void makeEmpty() { for( int i = 0; i < theLists.length; i++ ) theLists[ i ].clear(); currentSize = 0; } private int myhash(T element) { int hashValue = element.hashCode(); hashValue %= theLists.length; if(hashValue < 0) hashValue += theLists.length; return hashValue; } public void showAll() { for(int i=0; i<theLists.length; i++) System.out.println("Chain "+i+" : "+theLists[i]); } public static void main(String[] args) { SeparateChaining<String> sc = new SeparateChaining(7); sc.insert("hello"); sc.insert("java"); sc.insert("world"); sc.insert("programming"); sc.insert("separate"); sc.insert("chaining"); System.out.println("java is present " + sc.contains("java")); sc.showAll(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter