I have a custom hashtable implementation in java.
public class HashSet<T> implements HashTableInterface<T> {
private static int DEFAULT_ARRAY_SIZE = 10;
private T[] items;
public HashSet() {
final T[] items = (T[]) new Object[DEFAULT_ARRAY_SIZE];
this.items = items;
}
#Override
public boolean add(T item) {
int index = getIndex(item);
do {
if (items[index] != null) {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
} else {
items[index] = item;
break;
}
} while (index != getIndex(item));
return true;
}
#Override
public boolean remove(T item) {
if (contains(item)) {
items[getIndex(item)] = null;
return true;
} else {
return false;
}
}
#Override
public boolean contains(T item) {
T itemArray = items[getIndex(item)];
if (item.equals(itemArray)) {
return true;
} else {
int index = (getIndex(item) + 1) % DEFAULT_ARRAY_SIZE;
do {
if (items[index] != null) {
if (items[index].equals(item)) {
return true;
} else {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
}
} else {
break;
}
} while (index != getIndex(item));
}
return items[getIndex(item)] != null;
}
#Override
public int getIndex(T item) {
return item.hashCode() % DEFAULT_ARRAY_SIZE;
}
#Override
public int size() {
int count = 0;
for (T item : items) {
if (item != null) {
count++;
}
}
return count;
}
#Override
public String toString() {
return items.toString();
}}
In my add method I want to check if the place where the item would be stored is free, if not it should go to the next index. Until it finds an empty place.
My code works but I think, there could be a better way to do this.
public boolean add(T item) {
int index = getIndex(item);
do {
if (items[index] != null) {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
} else {
items[index] = item;
break;
}
} while (index != getIndex(item));
return true;
}
I have the same problem in the contains method
public boolean contains(T item) {
T itemArray = items[getIndex(item)];
if (item.equals(itemArray)) {
return true;
} else {
int index = (getIndex(item) + 1) % DEFAULT_ARRAY_SIZE;
do {
if (items[index] != null) {
if (items[index].equals(item)) {
return true;
} else {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
}
} else {
break;
}
} while (index != getIndex(item));
}
return items[getIndex(item)] != null;
}
There a many different ways to do collision avoidance, what you did is called "Linear Probing".
There is also (reference here)
Quadratic probing
Double hashing
And schemes that use linked lists for colliding values.
All of these have different tradeoffs which you should inform yourself on to make an informed decision.
Related
I have a method that tests if a binary search tree is an AVL tree, and am not getting the results i want.
here is the code :fg(left child) - fd(right child) - ag(left tree) - Noeud(node) - racine(root)
package cm5_TP_algo;
class Noeud {
int height;
int v;
Noeud fg;
Noeud fd;
Noeud(Noeud fg,int v,Noeud fd){
this.fg=fg;
this.v=v;
this.fd=fd;
}
public String toString(){
String sb = "[";
if (fg!=null)sb += fg.toString();
sb += v;
if (fd!=null)sb += fd.toString();
return sb + "]";
}
boolean testABR(int min, int max) {
if (fg != null && !fg.testABR(min, v)) {
return false;
}
if (fd != null && !fd.testABR(v, max)) {
return false;
}
return v >= min && v <= max;
}
public int calculateHeight() {
int heightLeft = (fg == null) ? 0 : fg.calculateHeight();
int heightRight = (fd == null) ? 0 : fd.calculateHeight();
height = Math.max(heightLeft, heightRight) + 1;
return height;
}
}
public class Arbre {
Noeud racine;
public Arbre(){ racine=null;}
public Arbre(Arbre ag, int v, Arbre ad) {
racine = new Noeud (ag.racine, v, ad.racine);
}
public String toString() {
if (racine == null) { return ""; }
else { return racine.toString(); }
}
public boolean testABR() {
return racine == null || racine.testABR(Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public void inser(int value){
if(racine == null)
racine = new Noeud(null, value, null);
else{
inser(value, racine);
}
}
public void inser(int value, Noeud racine){
if ( racine.v > value && racine.fg == null ) {
racine.fg = new Noeud(null, value, null);
return;
}
else if(racine.v > value && racine.fg != null){
inser(value, racine.fg);
}
if (racine.v < value && racine.fd == null ) {
racine.fd = new Noeud(null, value, null);
return;
}
else if(racine.v < value && racine.fd != null) {
inser(value, racine.fd);
}
}
public boolean membre(int value) {
if(racine == null)
return false;
if(racine.v == value)
return true;
if(racine.v < value && racine.fd != null )
return membre(value, racine.fd);
if(racine.v > value && racine.fg != null)
return membre(value, racine.fg);
return false;
}
private boolean membre(int value, Noeud racine) {
if(racine.v == value)
return true;
if(racine.v < value && racine.fd != null )
return membre(value, racine.fd);
if(racine.v > value && racine.fg != null)
return membre(value, racine.fg);
return false;
}
public void updateHeights() {
if (racine != null) {
racine.calculateHeight();
}
}
private int getHeight(Noeud noeud) {
if (noeud == null) {
return -1;
}
return noeud.height;
}
public boolean testAVL() {
updateHeights();
return checkBalanced();
}
private boolean checkBalanced() {
return checkBalanced(this.racine);
}
private boolean checkBalanced(Noeud node) {
if (node == null) return true;
int balance = getHeight(node.fd) - getHeight(node.fg);
if (Math.abs(balance) > 1) {return false;}
return checkBalanced(node.fd) && checkBalanced(node.fg);
}
public static void main(String[] args) {
Arbre t1= new Arbre( new Arbre() ,1, new Arbre() );
Arbre t2= new Arbre(
new Arbre(
new Arbre( )
, 12,
new Arbre( ))
, 13,
new Arbre() );
Arbre t3= new Arbre( t1,15,t2);
Arbre t4= new Arbre( t2,16,t3);
System.out.println(t1+":"+t1.testAVL());
System.out.println(t2+":"+t2.testAVL());
System.out.println(t3+":"+t3.testAVL());
System.out.println(t4+":"+t4.testAVL());
}
}
The expected result is :
[[12]13]:true
[115[[12]13]]:false
[[[12]13]16[115[[12]13]]]:false
But what i get is :
[[12]13]:false
[115[[12]13]]:false
[[[12]13]16[115[[12]13]]]:false
Is the problem with the testAVL or the updateHeights ?
I'm currently struggling to write a union() method for my AVL (auto balancing) tree IntegerSet Class.
Some requirements for my class:
Integer sets are ordered
Methods must be at most O(NlogN) time
You may not use a built in tree Java library. You must implement your own tree
The union() method: This is the mathematical union on two sets which creates a new set that contains all the elements from both sets. For example, [1, 2, 3] U [2, 3, 5, 6] results in a new set [1, 2, 3, 5, 6].
My thought was to copy the unique elements of each tree into an array, then use my constructor to create a new tree from that array. However, I haven't been able to copy the elements into an array correctly. I'm also wondering if there's a better way to be doing this.
My current code is below:
package dataStructures.AVL;
import java.util.LinkedList;
import java.util.Queue;
public class IntegerSet {
private Node root;
private int size;
public IntegerSet() {
clear();
}
public IntegerSet(int array[]) {
// Add elements of array to Binary Search Tree
for (int i = 0; i < array.length; i++) {
add(array[i]);
}
}
public int magnitude() {
return size;
}
public void clear() {
root = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean add(int newItem) {
boolean added = false;
if (isEmpty()) {
root = new Node(newItem);
size += 1;
added = true;
} else {
added = add(null, root, newItem);
}
return added;
}
private boolean add(Node parent, Node current, int data) {
boolean added = false;
if (current == null) {
int result = data - parent.data; // data.compareTo(parent.data);
if (result < 0) {
parent.leftChild = new Node(data);
} else {
parent.rightChild = new Node(data);
}
size += 1;
return true;
} else if ((data - current.data) < 0) { // (data.compareTo(current.data) < 0) {
added = add(current, current.leftChild, data);
} else if (data - current.data > 0) { // (data.compareTo(current.data) > 0) {
added = add(current, current.rightChild, data);
} else {
return false;
}
fixHeight(current);
if (added) {
rebalance(parent, current);
}
return added;
}
public boolean remove(int itemToRemove) {
if (isEmpty()) {
return false;
} else if (size == 1 && root.data == itemToRemove) { // (size == 1 && root.data.equals(itemToRemove)) {
clear();
return true;
} else if (removeTraversal(null, root, itemToRemove)) {
size -= 1;
return true;
} else {
return false;
}
}
private boolean removeTraversal(Node parent, Node current, int data) {
boolean removed = true;
if (current == null) {
return false;
} else if (data - current.data < 0) { // (data.compareTo(current.data) < 0) {
removed = removeTraversal(current, current.leftChild, data);
} else if (data - current.data > 0) { // (data.compareTo(current.data) > 0) {
removed = removeTraversal(current, current.rightChild, data);
} else {
removeNode(parent, current);
}
fixHeight(current);
if (removed) {
rebalance(parent, current);
}
return removed;
}
private void removeNode(Node parent, Node current) {
if (current.leftChild == null && current.rightChild == null) {
// Remove leaf node
removeCase1(parent, current);
} else if (current.leftChild != null && current.rightChild == null) {
// Remove node with no right child
removeCase2(parent, current);
} else if (current.leftChild == null && current.rightChild != null) {
// Remove node with no left child
removeCase3(parent, current);
} else {
// Remove node with both children
removeCase4(parent, current);
}
fixHeight(parent);
}
private void removeCase1(Node parent, Node current) {
if (parent == null) {
root = null;
} else if (parent.leftChild == current) {
parent.leftChild = null;
} else {
parent.rightChild = null;
}
}
private void removeCase2(Node parent, Node current) {
if (parent == null) {
root = root.leftChild;
} else if (parent.leftChild == current) {
parent.leftChild = current.leftChild;
} else {
parent.rightChild = current.leftChild;
}
current.leftChild = null;
}
private void removeCase3(Node parent, Node current) {
if (parent == null) {
root = root.rightChild;
} else if (parent.leftChild == current) {
parent.leftChild = current.rightChild;
} else {
parent.rightChild = current.rightChild;
}
current.rightChild = null;
}
private void removeCase4(Node parent, Node current) {
Node leftMost = current.rightChild;
Node leftMostParent = current;
while (leftMost.leftChild != null) {
leftMostParent = leftMost;
leftMost = leftMost.leftChild;
}
current.data = leftMost.data;
removeNode(leftMostParent, leftMost);
rebalance(current, current.rightChild);
}
public boolean contains(int itemToFind) {
if (isEmpty()) {
return false;
} else {
Node temp = root;
while (temp != null) {
int result = itemToFind - temp.data;
if (result < 0) {
temp = temp.leftChild;
} else if (result > 0) {
temp = temp.rightChild;
} else {
return true;
}
}
}
return false;
}
public IntegerSet union(IntegerSet other) {
return null;
}
public IntegerSet intersection(IntegerSet other) {
return null;
}
public IntegerSet difference(IntegerSet other) {
return null;
}
public IntegerSet symmetricDifference(IntegerSet other) {
return null;
}
public int getMin() {
if (isEmpty()) {
throw new EmptyCollectionException("Cannot remove from an empty tree.");
} else {
Node temp = root;
while (temp.leftChild != null) {
temp = temp.leftChild;
}
return temp.data;
}
}
public int getMax() {
if (isEmpty()) {
throw new EmptyCollectionException("Cannot remove from an empty tree.");
} else {
Node temp = root;
while (temp.rightChild != null) {
temp = temp.rightChild;
}
return temp.data;
}
}
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (node == null) {
return -1;
}
return Math.max(node.leftHeight, node.rightHeight);
}
private void fixHeight(Node node) {
if (node != null) {
node.leftHeight = getHeight(node.leftChild) + 1;
node.rightHeight = getHeight(node.rightChild) + 1;
}
}
private int balance(Node node) {
// If the balance > 1 imbalance is in left subtree
// If the balance < -1 imbalance is in right subtree
return node.leftHeight - node.rightHeight;
}
private Node rightRotation(Node n) {
Node c = n.leftChild;
Node t2 = c.rightChild;
c.rightChild = n;
n.leftChild = t2;
fixHeight(n);
fixHeight(c);
return c;
}
private Node leftRotation(Node n) {
Node c = n.rightChild;
Node t2 = c.leftChild;
c.leftChild = n;
n.rightChild = t2;
fixHeight(n);
fixHeight(c);
return c;
}
private void rebalance(Node parent, Node node) {
if (node == null) {
return;
}
// Imbalance in left subtree
if (balance(node) > 1) {
// Handles case III
if (balance(node.leftChild) < 0) {
// leftRotation
node.leftChild = leftRotation(node.leftChild);
}
if (parent == null) {
root = rightRotation(node);
} else if (parent.leftChild == node) {
parent.leftChild = rightRotation(node);
} else {
parent.rightChild = rightRotation(node);
}
// Imbalance in right subtree
} else if (balance(node) < -1) {
// Handle case IV
if (balance(node.rightChild) > 0) {
node.rightChild = rightRotation(node.rightChild);
}
if (parent == null) {
root = leftRotation(node);
} else if (parent.leftChild == node) {
parent.leftChild = leftRotation(node);
} else {
parent.rightChild = leftRotation(node);
}
}
}
#Override
public String toString() {
return levelOrderString();
}
public String levelOrderString() {
StringBuffer sb = new StringBuffer();
sb.append("{");
if (!isEmpty()) {
Queue<Node> q = new LinkedList<>();
q.add(root);
Node current = null;
while (!q.isEmpty()) {
current = q.remove();
if (current.leftChild != null) {
q.add(current.leftChild);
}
if (current.rightChild != null) {
q.add(current.rightChild);
}
sb.append(current);
if (!q.isEmpty()) {
sb.append(", ");
}
}
}
sb.append("}");
return sb.toString();
}
public String inOrderToString() {
StringBuffer sb = new StringBuffer();
sb.append("{ ");
inOrderToString(root, sb);
sb.append(" }");
return sb.toString();
}
private void inOrderToString(Node current, StringBuffer sb) {
if (current != null) {
inOrderToString(current.leftChild, sb);
if (current.leftChild != null) {
sb.append(", ");
}
sb.append(current.data);
if (current.rightChild != null) {
sb.append(", ");
}
inOrderToString(current.rightChild, sb);
}
}
// You may add any methods or constructors
// to this class that you see fit.
private class Node {
private int data;
private Node leftChild;
private Node rightChild;
private int leftHeight;
private int rightHeight;
public Node(int data) {
this.data = data;
}
public String toString() {
String formatter = "(%s | %s | %s)";
String leftString = leftChild != null ? Integer.toString(leftChild.data) : "";
String rightString = rightChild != null ? Integer.toString(rightChild.data) : "";
return String.format(formatter, Integer.toString(data), leftString, rightString);
}
}
}
im trying to make a linked list of generic objects. i have the linked list made now i have to load a file of movies(in movie class i have genre,rating, title).first i need to load a CVS file of movies the create Hash Table Object which contains an array of Linked List objects which in turn stores the Movies. so for example in a movie class i will have genre and genre can be many. i want to get hash code of genre and then store that in a hash table of arrayed linked list. that's what im using the LoadingMovie class for.
i dont know what im doing as it my first time working with hash tables and link list etc.this is what i have so far:
public class List<T> {
private Node<T> head;
private Node<T> tail;
private int count;
public void append(T d) {
if (head == null) {
head = tail = new Node<T>(d);
} else {
tail.insertAfter(d);
tail = tail.getNext();
count++;
}
}
public void prepend(T d) {
if (head == null) {
head = tail = new Node<T>(d);
} else {
head.insertBefore(d);
head = head.getPrevious();
count++;
}
}
public void removeHead() {
if (head == null) {
return;
} else if (head == tail) {
head = tail = null;
count--;
return;
}
head = head.getNext();
count--;
}
public ListIterator<T> getIterator() {
return new ListIterator<T>(this, head);
}
public void add(ListIterator<T> iter, T data) {
if (iter.getList() != this) {
return;
}
if (!iter.isValid()) {
append(data);
} else {
iter.getCurrentNode().insertAfter(data);
count++;
if (iter.getCurrentNode() == tail) {
tail = iter.getCurrentNode().getNext();
}
}
}
public void remove(ListIterator<T> iter) {
if (iter.getList() != this) {
return;
}
Node<T> node = iter.getCurrentNode();
if (node == null) {
return;
} else if (node == head) {
removeHead();
} else if (node == tail) {
removeTail();
} else {
Node<T> ptn = node.getPrevious();
ptn.setNext(node.getNext());
node.getNext().setPrevious(ptn);
iter.advance();
count--;
}
}
public void removeTail() {
if (head == null) {
} else if (head == tail) {
head = tail = null;
count--;
} else {
Node<T> node = head;
while (node.getNext() != tail) {
node = node.getNext();
}
tail = node;
tail.setNext(null);
count--;
}
}
public void display() {
ListIterator<T> iter = getIterator();
do {
System.out.println(iter.item()+ " , ");
iter.advance();
} while (iter.isValid());
}
public void displayReverse() {
ListIterator<T> iter = getIterator();
iter.end();
do {
System.out.print(iter.item() + " , ");
iter.previous();
} while (iter.isValid());
}
public Node<T> getHead() {
return head;
}
public Node<T> getTail() {
return tail;
}
public int getCount() {
return count;
}
public void setHead(Node<T> head) {
this.head = head;
}
public void setTail(Node<T> tail) {
this.tail = tail;
}
public void setCount(int count) {
this.count = count;
}
#Override
public int hashCode() {
int hash = 5;
hash = 89 * hash + Objects.hashCode(this.head);
hash = 89 * hash + Objects.hashCode(this.tail);
hash = 89 * hash + this.count;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final List<?> other = (List<?>) obj;
if (!Objects.equals(this.head, other.head)) {
return false;
}
if (!Objects.equals(this.tail, other.tail)) {
return false;
}
if (this.count != other.count) {
return false;
}
return true;
}
this is the node class :
public class Node<T> {
T anElement;
Node<T> next;
Node<T> previous;
public Node() {
anElement = null;
next = null;
}
public Node(T elem) {
anElement = elem;
next = null;
}
public T getAnElement() {
return anElement;
}
public void setAnElement(T anElement) {
this.anElement = anElement;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
public Node<T> getPrevious() {
return previous;
}
public void setPrevious(Node<T> previous) {
this.previous = previous;
}
#Override
public String toString() {
return "MyNode{" + "anElement=" + anElement + ", next=" + next + '}';
}
public void insertAfter(T nextData) {
if (nextData == null) {
return;
}
Node s = new Node(nextData);
s.setNext(next);
s.setPrevious(this);
if (next != null) {
next.setPrevious(s);
}
next = s;
}
public void insertBefore(T data) {
if (data == null) {
return;
}
Node s = new Node(data);
s.setNext(this);
s.setPrevious(previous);
if (previous != null) {
previous.setNext(s);
}
previous = s;
}
}
this is the load file class :
public class LoadingMovies {
private static final int size = 127;
private static HashMap<String, Movies> hash = new HashMap(size);
public static void loadMovies(String filename) {
String split = ","; //split with comma
try {
Scanner in = new Scanner(new File(filename));
String wordIn;
//List<Movies> linked = new List<>();
while (in.hasNextLine()) {
wordIn = in.nextLine();
String splitter[] = wordIn.split(split);
String movieTitle = splitter[0];
String movieGenre = splitter[1];
String ageRating = splitter[2];
double scoreRating = Double.parseDouble(splitter[3]);
Movies movie = new Movies();
movie.setTitle(movieTitle);
movie.setGenre(movieGenre);
movie.setAgeRating(ageRating);
movie.setScoreRating(scoreRating);
hash.find(movie.getGenre());
hash.insert(movie.getGenre(), movie);
hash.display();
}
} catch (FileNotFoundException e) {
System.out.println("Exception occured in the loadMovies() method in the Loadingovies class");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String filename = input.next();
loadMovies(filename);
}
this is the hash map method:
public class HashMap<KeyType,DataType>
{
private int count;
private int size;
private List<HashEntry<KeyType,DataType>> [] table;
public HashMap() {
}
public HashMap(int num)
{
size = num;
table = new List[num];
for(int i = 0; i < num; i++){
table[i] = new List<HashEntry<KeyType,DataType>>();
}
}
public void insert(KeyType key, DataType data){
if(key != null && data != null){
int hash = key.hashCode() % size;
HashEntry<KeyType, DataType> obj = new HashEntry(key, data);
table[hash].append(obj);
count++;
}
}
public void display(){
for(int i = 0 ; i < size; i++){
System.out.println("tables" + i + " ");
table[i].display();
}
}
public DataType find(KeyType key){
int hash = key.hashCode() % size;
List<HashEntry<KeyType,DataType>> list = table[hash];
ListIterator <HashEntry<KeyType, DataType>> iter = list.getIterator();
while(iter.isValid()){
if(iter.item().getKey().equals(key)){
return iter.item().getData();
}
iter.advance();
}
return null;
}
public void remove(KeyType key){
int hash = key.hashCode() % size;
List<HashEntry<KeyType,DataType>> list = table[hash];
ListIterator <HashEntry<KeyType, DataType>> iter = list.getIterator();
while(iter.isValid()){
if(iter.item().getKey().equals(key)){
list.remove(iter);
}
iter.advance();
}
}
}
and this is what i have for movie class:
public class Movies {
private String title;
private String genre;
private String ageRating;
private double scoreRating;
public Movies() {
title = "";
genre = "";
ageRating = "";
scoreRating = 0;
}
public Movies(String title, String genre, String ageRating, double scoreRating) {
this.title = title;
this.genre = genre;
this.ageRating = ageRating;
this.scoreRating = scoreRating;
}
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public String getAgeRating() {
return ageRating;
}
public double getScoreRating() {
return scoreRating;
}
public void setTitle(String title) {
this.title = title;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setAgeRating(String ageRating) {
this.ageRating = ageRating;
}
public void setScoreRating(double scoreRating) {
this.scoreRating = scoreRating;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Movies other = (Movies) obj;
if (!Objects.equals(this.title, other.title)) {
return false;
}
if (!Objects.equals(this.genre, other.genre)) {
return false;
}
if (!Objects.equals(this.ageRating, other.ageRating)) {
return false;
}
if (Double.doubleToLongBits(this.scoreRating) != Double.doubleToLongBits(other.scoreRating)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 11;
hash = (int) ((hash * 10) + scoreRating);
if (this.title != null) {
hash = (hash * 10) + title.hashCode();
}
if (this.genre != null) {
hash = (hash * 10) + genre.hashCode();
}
if (this.ageRating != null) {
hash = (hash * 10) + ageRating.hashCode();
}
return hash;
}
#Override
public String toString() {
String statement = "Movie Title:" + title + "\n" + "Movie Genre:" + genre + "\n" + "Age Rating: " + ageRating + "\n" + "User Score: " + scoreRating + "\n";
return statement;
}
what am i doing wrong please :(
i get null pointer exceptions arrayoutofboundexceptions
some movies printing and i get loads of tables thatare null :'(
The problem here is in mapping objects to buckets. This line of code...
int hash = key.hashCode() % size;
is capable of producing a negative value. key.hashCode() can be a negative number, and the result of the % operator on a negative number is a negative number. That's what causes your ArrayIndexOutOfBounds exception. The simplest solution is to use the absolute value of the hashCode...
int hash = Math.abs(key.hashCode()) % size;
I am currently trying to take a text file, and break the text file into words. I am then attempting to store each word as a node in a binary tree. After doing so I also try to print the binary tree. For some reason when i run my code i am now getting caught in an infinite loop but i don't understand where or why that is if you can see where i am getting caught that would be a great help thanks
public class Tester {
public static void main(String[] args) throws FileNotFoundException {
Tester run = new Tester();
run.it();
}
public void it() throws FileNotFoundException {
BTree theTree = new BTree();
String str = this.readInFile();
int position = 0;
String newWord = this.breakIntoWords(str, position);
while(newWord != null){
theTree.add(newWord);
newWord = this.breakIntoWords(str, position);
}
theTree.print();
}
public String readInFile() throws FileNotFoundException {
String myFile = "";
int numWords = 0;
Scanner myScan = new Scanner(new File("Dracula.txt"));
while(myScan.hasNext() == true) {
myFile += myScan.nextLine() + " ";
}
return myFile;
}
public String breakIntoWords(String myFile, int position) {
String nextWord = null;
char next = myFile.charAt(position);
next = Character.toLowerCase(next);
// First trim beginning
while (((next < 'a') || (next > 'z')) && !Character.isDigit(next)) {
position++;
next = myFile.charAt(position);
next = Character.toLowerCase(next);
}
// Now pull only letters or numbers until we hit a space
while(!Character.isWhitespace(next)) {
if (Character.isLetterOrDigit(next)) {
nextWord += myFile.charAt(position);
}
position++;
next = myFile.charAt(position);
}
return nextWord;
}
public class BTree {
private BTNode root;
private int nodeCount;
public boolean add(String word){
BTNode myNode = new BTNode(word);
if(root == null){
root = myNode;
nodeCount++;
return true;
}
if(findNode(word)){
int tmp = myNode.getNumInstance();
tmp++;
myNode.setNumInstance(tmp);
return false;
}
BTNode temp = root;
while(temp != null){
if(word.compareTo(temp.getMyWord()) < 0) {
if(temp.getRightChild() == null){
temp.setLeftChild(myNode);
nodeCount++;
return true;
} else {
temp = temp.getRightChild();
}
} else {
if(temp.getLeftChild() == null){
temp.setLeftChild(myNode);
nodeCount++;
return true;
} else {
temp = temp.getLeftChild();
}
}
}
return false;
}
public boolean findNode(String word) {
return mySearch(root, word);
}
private boolean mySearch(BTNode root, String word) {
if (root == null) {
return false;
}
if ((root.getMyWord().compareTo(word) < 0)) {
return true;
} else {
if (word.compareTo(root.getMyWord()) > 0) {
return mySearch(root.getLeftChild(), word);
} else {
return mySearch(root.getRightChild(), word);
}
}
}
public void print() {
printTree(root);
}
private void printTree(BTNode root) {
if (root == null) {
System.out.print(".");
return;
}
printTree(root.getLeftChild());
System.out.print(root.getMyWord());
printTree(root.getRightChild());
}
public int wordCount() {
return nodeCount;
}
You repeatedly call this.breakIntoWords(str, position) with the same str and position, using its return value to decide when to stop. Since nothing changes from the one iteration to the next, the loop never terminates.
I'm trying to override a method that adds a string to a list. But i want the method to not add the string if the string is a duplicate in the list. If it isn't a duplicate than add if not do nothing. Here is my code. I'm just confused why it is not working.
public class Hw6 <T extends Comparable<? super T>> implements SortedListInterface<T>
{
private ListInterface<T> list;
public Hw6()
{
list = new LList<T>();
}
#Override
public boolean add(T newEntry) {
boolean results = false;
if(!contains(newEntry))
{
list.add(newEntry);
results = true;
}
return results;
}
public boolean addPrivate(T newEntry)
{
int newPosition = Math.abs(getPosition(newEntry));
return list.add(newPosition, newEntry);
}
#Override
public boolean remove(T anEntry) {
boolean result = false;
int position = getPosition(anEntry);
if (position > 0)
{
list.remove(position);
result = true;
}
return result;
}
#Override
public int getPosition(T anEntry) {
int position = 1;
int length = list.getLength();
while((position <= length) && (anEntry.compareTo(list.getEntry(position)) > 0))
{
position++;
}
if ((position > length) || (anEntry.compareTo(list.getEntry(position)) != 0))
{
position = -position;
}
return position;
}
#Override
public T getEntry(int givenPosition) {
return list.getEntry(givenPosition);
}
#Override
public boolean contains(T anEntry) {
boolean found = false;
for (int index = 0; !found && (index < getLength()); index++)
{
if (anEntry.equals(list.getEntry(index)))
found = true;
}
return found;
}
#Override
public int getLength() {
// TODO Auto-generated method stub
return list.getLength();
}
#Override
public boolean isEmpty() {
if(getLength() == 0)
return true;
else
return false;
}
#Override
public boolean isFull() {
return false;
}
public static void main(String args[])
{
LList<String> list = new LList<String>();
list.add("brad");
list.add("nick");
list.add("brad");
for(int i = 1; i <= list.getLength(); i++)
{
System.out.println(list.getEntry(i));
}
}
}
here is my output. i don't want it to add brad because its a duplicate
brad
nick
brad
It is because in your test you are creating a LList object but you should be creating a Hw6 object.