Initialize an Item Array - java

I want to initialize an Item Array but can't figure it out.
Here is my code.
public class HashTable<Item> {
private int m; // hash table size
private Item[] T; // hash table
HashTable(int M)
{
m = M;
T = new Item[M];
for(int i=0;i<M;i++){
Item T[i] = null;
}
}
...
...
SOLUTION
T = (Item[])new Object[M];

I think what you need is something like:
for(int i=0;i<M;i++){
T[i] = new Item(); // call some constructor here
}
You have
Item T[i] = ...
in your loop, while it should be just
T[i] = ...
So try these hints.
Also do this:
T = (Item[])new Object[M];
as Kumar suggested in his reply.
The thing is that Item is not really a type here. You need
to read how generics are actually compiled into bytecode,
and you will see what happens under the hood.

You are trying to create the array of Generic type,Please look at this post.
How to create a generic array in Java?

Assuming you created the class item you could call it like this:
public class HashTable
{
private int tableSize; // hash table size
private Item[] table; // hash table
public static void main(String[] args)
{
// where 10 is the number of nodes
Item[] myTable = createHashTable(10);
}
private static Item[] createHashTable(int size)
{
Item[] table = new Item[size];
for(int i = 0; i < table.length; i++)
{
table[i] = new Item(i);
}
}
}
However if you want to see an example of a full HashTable implementation:
/*
* HashTable.java
*
*
*/
/**
* A class that implements a hash table that employs open addressing
* using either linear probing, quadratic probing, or double hashing.
*/
public class HashTable {
/* Private inner class for an entry in the hash table */
private class Entry {
private String key;
private LLList valueList; // all of the values with this key
private boolean hasBeenRemoved; // has this entry been removed?
private Entry(String key, int value) {
this.key = key;
valueList = new LLList();
valueList.addItem(value, 0);
hasBeenRemoved = false;
}
}
// parameters for the second hash function -- see h2() below
private static final int H2_MIN = 5;
private static final int H2_DIVISOR = 11;
// possible types of probing
public static final int LINEAR = 0;
public static final int QUADRATIC = 1;
public static final int DOUBLE_HASHING = 2;
public static final int NUM_PROBE_TYPES = 3;
private Entry[] table; // the hash table itself
private int probeType = LINEAR; // the type of probing
// keeps track of how many times we perform a probe of a given length
private int[] probeLengthCount;
public HashTable(int size, int probeType) {
if (probeType >= 0 && probeType < NUM_PROBE_TYPES)
this.probeType = probeType;
else
throw new IllegalArgumentException("invalid probeType: " +
probeType);
table = new Entry[size];
probeLengthCount = new int[size + 1];
for (int i = 0; i <= size; i++)
probeLengthCount[i] = 0;
}
public HashTable(int size) {
// Call the other constructor to do the work.
this(size, LINEAR);
}
/* first hash function */
private int h1(String key) {
int h1 = key.hashCode() % table.length;
if (h1 < 0)
h1 += table.length;
return h1;
}
/* second hash function */
private int h2(String key) {
int h2 = key.hashCode() % H2_DIVISOR;
if (h2 < 0)
h2 += H2_DIVISOR;
h2 += H2_MIN;
return h2;
}
/*
* probeIncrement - returns the amount by which the current index
* should be incremented to obtain the nth element in the probe
* sequence
*/
private int probeIncrement(int n, int h2) {
if (n <= 0)
return 0;
switch (probeType) {
case LINEAR:
return 1;
case QUADRATIC:
return (2*n - 1);
case DOUBLE_HASHING:
default:
return h2;
}
}
/*
* probe - attempt to find a slot in the hash table for the specified key.
*
* If key is currently in the table, it returns the index of the entry.
* If key isn't in the table, it returns the index of the first empty cell
* in the table.
* If overflow occurs, it returns -1.
*/
private int probe(String key) {
int i = h1(key); // first hash function
int h2 = h2(key); // second hash function
int positionsChecked = 1;
// keep probing until we get an empty position or a match
while (table[i] != null && !key.equals(table[i].key)) {
if (positionsChecked == table.length) {
probeLengthCount[positionsChecked]++;
return -1;
}
i = (i + probeIncrement(positionsChecked, h2)) % table.length;
positionsChecked++;
}
probeLengthCount[positionsChecked]++;
return i;
}
/**
* insert - insert the specified (key, value) pair in the hash table
*/
public void insert(String key, int value) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = h1(key);
int h2 = h2(key);
int positionsChecked = 1;
int firstRemoved = -1;
while (table[i] != null && !key.equals(table[i].key)) {
if (table[i].hasBeenRemoved && firstRemoved == -1)
firstRemoved = i;
if (positionsChecked == table.length)
break;
i = (i + probeIncrement(positionsChecked, h2)) % table.length;
positionsChecked++;
}
probeLengthCount[positionsChecked]++;
if (table[i] != null && key.equals(table[i].key))
table[i].valueList.addItem(value, 0);
else if (firstRemoved != -1)
table[firstRemoved] = new Entry(key, value);
else if (table[i] == null)
table[i] = new Entry(key, value);
else
throw new RuntimeException("overflow occurred");
}
/**
* search - search for the specified key, and return the
* associated list of values, or null if the key is not in the
* table
*/
public LLList search(String key) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = probe(key);
if (i == -1 || table[i] == null)
return null;
else
return table[i].valueList;
}
/**
* remove - remove from the table the entry for the specified key
*/
public void remove(String key) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = probe(key);
if (i == -1 || table[i] == null)
return;
table[i].key = null;
table[i].valueList = null;
table[i].hasBeenRemoved = true;
}
/**
* printStats - print the statistics for the table -- i.e., the
* number of keys and items, and stats for the number of times
* that probes of different lengths were performed
*/
public void printStats() {
int numProbes = 0;
int probeLengthSum = 0;
int numKeys = 0;
for (int i = 0; i < table.length; i++) {
if (table[i] != null && !table[i].hasBeenRemoved)
numKeys++;
}
System.out.println("\n" + numKeys + " keys");
System.out.println("probe-length stats:");
System.out.println("length\tcount");
for (int i = 1; i <= table.length; i++) {
if (probeLengthCount[i] != 0)
System.out.println(i + "\t" + probeLengthCount[i]);
numProbes += probeLengthCount[i];
probeLengthSum += (probeLengthCount[i] * i);
}
System.out.println("average probe length = " +
(double)probeLengthSum / numProbes);
}
}
Here is the second file for a Linked-Linked-List
/*
* LLList.java
*
*
*/
import java.util.*;
/**
* A class that implements our simple List interface using a linked list.
* The linked list includes a dummy head node that allows us to avoid
* special cases for insertion and deletion at the front of the list.
*/
public class LLList implements List {
// Inner class for a node. We use an inner class so that the LLList
// methods can access the instance variables of the nodes.
private class Node {
private Object item;
private Node next;
private Node(Object i, Node n) {
item = i;
next = n;
}
}
private Node head; // dummy head node
private int length; // # of items in the list
/**
* Constructs a LLList object for a list that is initially empty.
*/
public LLList() {
head = new Node(null, null);
length = 0;
}
/*
* getNode - private helper method that returns a reference to the
* ith node in the linked list. It assumes that the value of the
* parameter is valid.
*
* If i == -1, it returns a reference to the dummy head node.
*/
private Node getNode(int i) {
Node trav = head;
int travIndex = -1;
while (travIndex < i) {
travIndex++;
trav = trav.next;
}
return trav;
}
/** getItem - returns the item at position i in the list */
public Object getItem(int i) {
if (i < 0 || i >= length)
throw new IndexOutOfBoundsException();
Node n = getNode(i);
return n.item;
}
/**
* addItem - adds the specified item at position i in the list,
* shifting the items that are currently in positions i, i+1, i+2,
* etc. to the right by one. Always returns true, because the list
* is never full.
*
* We don't need a special case for insertion at the front of the
* list (i == 0), because getNode(0 - 1) will return the dummy
* head node, and the rest of insertion can proceed as usual.
*/
public boolean addItem(Object item, int i) {
if (i < 0 || i > length)
throw new IndexOutOfBoundsException();
Node newNode = new Node(item, null);
Node prevNode = getNode(i - 1);
newNode.next = prevNode.next;
prevNode.next = newNode;
length++;
return true;
}
/**
* removeItem - removes the item at position i in the list,
* shifting the items that are currently in positions i+1, i+2,
* etc. to the left by one. Returns a reference to the removed
* object.
*
* Here again, we don't need a special case for i == 0 (see the
* note accompanying addItem above).
*/
public Object removeItem(int i) {
if (i < 0 || i >= length)
throw new IndexOutOfBoundsException();
Node prevNode = getNode(i - 1);
Object removed = prevNode.next.item;
prevNode.next = prevNode.next.next;
length--;
return removed;
}
/** length - returns the number of items in the list */
public int length() {
return length;
}
/**
* isFull - always returns false, because the linked list can
* grow indefinitely and thus the list is never full.
*/
public boolean isFull() {
return false;
}
/**
* toString - converts the list into a String of the form
* [ item0 item1 ... ]
*/
public String toString() {
String str = "[ ";
Node trav = head.next; // skip over the dummy head node
while (trav != null) {
str += (trav.item + " ");
trav = trav.next;
}
str += "]";
return str;
}
/**
* iterator - returns an iterator for this list
*/
public ListIterator iterator() {
return new LLListIterator();
}
/*
*** private inner class for an iterator over an LLList ***
*/
private class LLListIterator implements ListIterator {
private Node nextNode; // the next node to visit
private Node lastVisitedNode; // the most recently visited node
public LLListIterator() {
nextNode = head.next;
lastVisitedNode = null;
}
/**
* hasNext - does the iterator have additional items to visit?
*/
public boolean hasNext() {
return (nextNode != null);
}
/**
* next - returns a reference to the next Object in the iteration
*/
public Object next() {
if (nextNode == null)
throw new NoSuchElementException();
Object item = nextNode.item;
lastVisitedNode = nextNode;
nextNode = nextNode.next;
return item;
}
}
}

Related

Trouble with accurately removing Nodes in a LinkedList

I wrote the following class for building a LinkedList with single values on top of a given code template.
.
.
public class LinkedElement<T> {
private T name;
private LinkedElement<T> link;
public LinkedElement(T value) {
this.name = value;
}
/**
* Returns the value of the i-th linked element, assuming the current element to
* be at index 0.
*
* #param i 0-based index of the element whose value to return.
* #return the i-th element's value, or {#code null} if there is no element with
* that index.
*/
public T get(int i) {
int iterator = i;
if (iterator == 0) {
return this.name;
}
if (this.link == null) {
iterator = 0;
return null;
}
if (iterator > 0) {
iterator = iterator - 1;
return this.link.get(iterator);
}
return null;
}
/**
* Adds a new linked element holding the given value at the end of the linked
* elements.
*
* #param newVal the new value.
*/
public void add(T newVal) {
if (this.link == null) {
this.link = new LinkedElement(newVal);
} else {
this.link.add(newVal);
}
}
**/**
* Removes the i-th element from the linked elements. If {#code i == 0}, this
* will effectively remove the head element. Thus, this method returns the
* linked element that is the new head element.
*
* #param i index of the element to remove.
* #return the new head element.
*/
public LinkedElement<T> remove(int i) {
// Store i as changeable iterator
int iterator = i;
// Store current head element;
LinkedElement<T> tempNode = this;
// If head element itself is to be removed
if (iterator == 0) {
if (this.link != null) {
this.name = this.link.name;
this.link = this.link.link;
}
if (this.link == null) {
this.name = null;
this.link = null;
}
return this;
// If the element is further down in the linkedlist
// iterate through list and invoke "remove" at the desired position inside
// the list
}
if (iterator > 0) {
iterator = iterator - 1;
return this.link.remove(iterator);
}
return null;**
}
}
The "remove" method seems to work fine when I remove just one element and print the elements out one by one. The trouble starts when I declare a new headElement through a remove method (which returns the new headElement in that respective list)
public static void main(String[] args) {
// An example
LinkedElement<String> headElement = new LinkedElement<String>("Yo!");
headElement.add("LA");
headElement.add("is");
headElement.add("about");
headElement.add("to");
headElement.add("witness");
headElement.add("another");
headElement.add("sunny");
headElement.add("day!");
System.out.println(headElement.get(7)); // prints "sunny"
headElement = headElement.remove(6); // removes "another"
headElement = headElement.remove(0); // removes "Yo!"
System.out.println(headElement.get(0)); // prints "sunny"
}
The expected output should be:
sunny
sunny
but I get
sunny
null
Question updated because I worded myself poorly.
because your headElement after remove(0) is:
LinkedElement<String> headElement = new LinkedElement<String>("what's");//0
headElement.add("up!");//1
headElement.add("That's");//2
headElement.add("Mitch");//3
headElement.add("Jones!");//4
and then you remove(2) from result above: which is "That's"; //at index 2
so yo get:
LinkedElement<String> headElement = new LinkedElement<String>("what's");//0
headElement.add("up!");//1
headElement.add("Mitch");//2
headElement.add("Jones!");//3
Try to print after remove(0) and you can get what is happening!
Try this:
public LinkedElement<T> remove(int i) {
int iterator = i;
// Store current head element;
LinkedElement<T> tempNode = this;
// If head element itself is to be removed
if (iterator == 0) {
if (tempNode.link != null) {
tempNode.name = tempNode.link.name;
tempNode.link = tempNode.link.link;
}
if (tempNode.link == null) {
tempNode.name = null;
tempNode.link = null;
}
return tempNode;
// If the element is further down in the linkedlist
// iterate through list and invoke "remove" at the desired position inside
// the list
}
if (iterator > 0) {
iterator = iterator - 2;
return tempNode.link.remove(iterator);
}
return tempNode;
}
Might try the following
public class LinkedElement<T> {
private T value;
private LinkedElement<T> linkToNextElement;
public LinkedElement(T element) {
value = element;
linkToNextElement = null;
}
public static void main(String args[]) {
LinkedElement<String> head = new LinkedElement("a");
head.add("b");
head.add("c");
head.add("d");
head.add("e");
LinkedElement<String> newHead = head;
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(1)###");
newHead = head.remove(1);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(3)###");
newHead =head.remove(3);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(0)###");
newHead =head.remove(0);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(0)###");
newHead =head.remove(0);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(i)###");
newHead =head.remove(7);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(0)###");
newHead =head.remove(0);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
//empty List
if(newHead == null)
{
System.out.println("Head: value= NULL : no value for emplty list" );
}
}
/**
* Returns the value of the i-th linked element, assuming the current element to
* be at index 0.
*
* #param i 0-based index of the element whose value to return.
* #return the i-th element's value, or {#code null} if there is no element with
* that index.
*/
public T get(int i) {
int counter = 0;
LinkedElement<T> currElement = this;
if (i == 0) {
return value;
}
while (counter < i) {
if (currElement.linkToNextElement != null) {
currElement = currElement.linkToNextElement;
} else {
return null;
}
counter++;
}
return currElement.value;
}
/**
* Adds a new linked element holding the given value at the end of the linked
* elements.
*
* #param newVal the new value.
*/
public void add(T newVal) {
if (linkToNextElement == null) {
linkToNextElement = new LinkedElement<T>(newVal);
} else {
linkToNextElement.add(newVal);
}
}
/**
* Removes the i-th element from the linked elements. If {#code i == 0}, this
* will effectively remove the head element. Thus, this method returns the
* linked element that is the new head element.
*
* #param i index of the element to remove.
* #return the new head element.
*/
public LinkedElement<T> remove(int i) {
int counter = 0;
LinkedElement<T> currElement = this;
LinkedElement<T> prevElement = null;
LinkedElement<T> nextElement = null;
if (i == 0) {
if (currElement.linkToNextElement != null) {
nextElement = currElement.linkToNextElement;
value = nextElement.value;
if (nextElement.linkToNextElement != null) {
linkToNextElement = nextElement.linkToNextElement;
} else {
linkToNextElement = null;
}
// ;
return nextElement;
} else {
value = null;
linkToNextElement = null;
}
return linkToNextElement;
}
while (counter < i) {
if (currElement.linkToNextElement != null) {
prevElement = currElement;
currElement = currElement.linkToNextElement;
} else {
return this;
}
counter++;
}
if (currElement.linkToNextElement != null) {
nextElement = currElement.linkToNextElement;
prevElement.linkToNextElement = nextElement;
}
// last element
else {
prevElement.linkToNextElement = null;
}
return this;
}
}
Output
list[0]=a
list[1]=b
list[2]=c
list[3]=d
list[4]=e
list[5]=null
list[6]=null
Head: value=a
###remove(1)###
list[0]=a
list[1]=c
list[2]=d
list[3]=e
list[4]=null
list[5]=null
list[6]=null
Head: value=a
###remove(3)###
list[0]=a
list[1]=c
list[2]=d
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=a
###remove(0)###
list[0]=c
list[1]=d
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=c
###remove(0)###
list[0]=d
list[1]=null
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=d
###remove(7)###
list[0]=d
list[1]=null
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=d
###remove(0)###
list[0]=null
list[1]=null
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value= NULL : no value for empty list

How do I remove an element from a doubly circular linked list properly?

I have to implement a doubly circular linked list using my own constructor, I am pretty much done but can not figure out why the remove method is not working.
I have done plenty of research but I have had difficulties finding anything that matches my needs. The problem is that I do not have a permanent head and tail pointer, like usually in a doubly linked list but must work with the "header" as the starting as well as the ending point.
Constructor with the header element
public MyDoubleLinkedList() {
header = new DEntry(0, null, null);
header.next = header;
header.previous = header;
size = 0;
}
Inner class for the listEntrys
class DEntry {
/** the data element represented by this entry */
private final int data;
/** reference to the previous element in the list */
private DEntry previous;
/** reference to the next element in the list */
private DEntry next;
/**
* #param data the data object this entry represents
* #param previous reference to the previous element in the list
* #param next reference to the next element in the list
*/
public DEntry(int data, DEntry previous, DEntry next) {
this.data = data;
this.previous = previous;
this.next = next;
}
}
Method to add to the list:
/**
* Adds a new element into the list at the position specified
*
* #param position the 0 based position at which to add the passed value
* #param value the value to add
* #return 0 if adding was successful, -1 if not
*/
public int add(int position, int value) {
// TODO: please put your code here
DEntry listEntry = new DEntry(value, null, null);
DEntry temp = header;
int i = 0;
if (position < 0 || position > size) {
return -1;
}
if (position == 0) {
temp = header;
} else {
while (i < position) {
temp = temp.next;
i++;
}
}
listEntry.next = temp.next;
listEntry.previous = temp.next;
temp.next = listEntry;
temp.next.previous = listEntry.next;
size++;
return 0;
}
Method to remove from the list
/**
* Removes an element at the position specified from the list
*
* #param position the 0 based position of the value to remove
* #return value of the removed entry if removing was successful, -1 if not
*/
public int remove(int position) {
// TODO: please put your code here
DEntry toBeDeleted = header;
if(position < 0 || position > size) {
return -1;
}
if(getEntry(position) == null) {
return -1;
} else {
toBeDeleted = getEntry(position);
}
int dataOfDeletedNode = toBeDeleted.data;
if(position == 0) {
header.previous.next = toBeDeleted.next;
header.next.previous = toBeDeleted.previous;
} else if(position == size){
toBeDeleted.previous.next = header.next;
toBeDeleted.next.previous = toBeDeleted.previous;
} else {
toBeDeleted.previous.next = toBeDeleted.next;
toBeDeleted.next.previous = toBeDeleted.previous;
}
size--;
System.out.println(dataOfDeletedNode);
return dataOfDeletedNode;
}
If I run the code
list.add(0, 10);
list.add(1, 20);
list.add(0, 30);
remove(1); // 10 should be deleted
Instead of 30, 20 I get just 20.
It seems that your main problem's source is add method. Actually, there is a great problem in linking new nodes in your code and that was the only problem I have detected by reading your code. Thus, your add method should be something like this:
public int add(int position, int value) {
DEntry listEntry = new DEntry(value, null, null);
DEntry temp = header;
if (position < 0 || position > size) {
return -1;
}
if (position == 0) {
temp = header;
} else {
int i = 0;
while (i < position) {
temp = temp.next;
i++;
}
}
listEntry.next = temp.next;
listEntry.previous = temp;
temp.next = listEntry;
size++;
return 0;
}
listEntry would be the next node after the temp one. Then it's previous pointer should point to the temp.
putting new node after a temp node does not need any change in previous link of the temp. So, the last linking you had in your code was problematic.
I could solve this problem in the meantime. It was indeed my add method that prevented my remove method to work properly.
Partially at fault was my while loop which stopped at (i
Here is what I came up with on the add method, and everything is workin fine.
public int add(int position, int value) {
// Creates a new listEntry
DEntry listEntry = new DEntry(value, null, null);
DEntry temp = header;
int i = 0;
if (position < 0 || position > size) {
return -1;
}
while (i <= position) {
temp = temp.next;
i++;
}
// setting the elements neighbours
listEntry.next = temp;
listEntry.previous = temp.previous;
// placing the new element between last and next
temp.previous.next = listEntry;
temp.previous = listEntry;
// places the new entry in the list
temp = listEntry;
size++;
return 0;
}

Array Out Of Bounds Exception Cannot find [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 110
at HeapPriorityQueue.hasLeft(HeapPriorityQueue.java:168)
at HeapPriorityQueue.bubbleDown(HeapPriorityQueue.java:111)
at HeapPriorityQueue.removeMin(HeapPriorityQueue.java:73)
at a4tester.testRandomArray(a4tester.java:224)
at a4tester.stressTest(a4tester.java:237)
at a4tester.main(a4tester.java:283)
I have been trying to find where the Out of bounds exception is coming from and it is driving me insane! It only arises when my HeapPriorityQueue is put through the stress test below.
Basically getting an array out of bounds exception when my code is ran through this stress test:
public static boolean testRandomArray (int count) {
PriorityQueue q = createNewPriorityQueue(count);
System.out.println("Testing size: " + count);
Random r = new Random();
for ( int i = 0; i < count; i++ )
{
int val = r.nextInt(1000000);
q.insert (val);
}
int oldVal = -1;
while (!q.isEmpty() )
{
int val = (int)((Integer)q.removeMin()).intValue(); // or a bug
if ( oldVal > val )
return false;
oldVal = val;
}
return true;
}
This is my Program:
public class HeapPriorityQueue implements PriorityQueue {
protected final static int DEFAULT_SIZE = 10000;
/* This array is where you will store the elements in the heap */
protected Comparable storage[];
/* Keep track of the current number of elements in the heap */
protected int currentSize;
/* You do not need to change this constructor */
public HeapPriorityQueue ()
{
this(DEFAULT_SIZE);
}
/* You do not need to change this constructor */
public HeapPriorityQueue(int size)
{
storage = new Comparable[size + 1];
currentSize = 0;
}
/*
* You need to change the implementation of every public method
* below this comment.
*
*/
public int size () {
return currentSize;
}
public boolean isEmpty () {
if(size() == 0)
return true;
return false;
}
public Comparable removeMin () throws HeapEmptyException {
if(isEmpty())
throw new HeapEmptyException();
Comparable returnValue = storage[1];
storage[1] = storage[currentSize];
storage[currentSize] = null;
currentSize--;
bubbleDown();
return returnValue;
}
public void insert ( Comparable k ) throws HeapFullException {
if(currentSize >= storage.length - 1)
throw new HeapFullException();
currentSize++;
storage[currentSize] = k;
bubbleUp();
}
/* Your instructor's solution used the following helper methods
*
* You do not need to use the same methods, but you may want to.
*/
/*
* A new value has just been added to the bottom of the heap
* "bubble up" until it is in the correct position
*/
private void bubbleUp () {
int index = currentSize;
while(parent(index) != 0 && storage[parent(index)].compareTo(storage[index]) > 0) {
swapElement(index, parent(index));
index = parent(index);
}
}
/*
* Because of a removeMin operation, a value from the bottom
* of the heap has been moved to the root.
*
* "bubble down" until it is in the right position
*/
private void bubbleDown() {
int index = 1;
while (hasLeft(index)) {
int sc = leftChild(index);
if (hasRight(index) && storage[leftChild(index)].compareTo(storage[rightChild(index)]) > 0) {
sc = rightChild(index);
}
if (storage[index].compareTo(storage[sc]) > 0) {
swapElement(index, sc);
}
else{
}
index = sc;
}
}
/*
* Swap the element at position p1 in the array with the element at
* position p2
*/
private void swapElement ( int p1, int p2 ) {
Comparable temp = storage[p1];
storage[p1] = storage[p2];
storage[p2] = temp;
}
/*
* Return the index of the parent of the node at pos
*/
private int parent ( int pos )
{
return (pos/2); // replace this with working code
}
/*
* Return the index of the left child of the node at pos
*/
private int leftChild ( int pos )
{
return (pos*2); // replace this with working code
}
/*
* Return the index of the right child of the node at pos
*/
private int rightChild ( int pos )
{
return (pos * 2)+1; // replace this with working code
}
/*
* Given the current number of elements in the heap, does the
* node at pos have a left child?
*
* Note that all internal nodes have at least a left child.
*
*/
private boolean hasLeft ( int pos )
{
if(storage[leftChild(pos)] != null)
return true;
return false; // replace this with working code
}
/*
* Given the current number of elements in the heap, does the
* node at pos have a right child?
*/
private boolean hasRight ( int pos ) {
if(storage[rightChild(pos)] != null)
return true;
return false; // replace this with working code
}
}
There are a few things that are potentially problematic:
private boolean hasLeft ( int pos )
{
if(storage[leftChild(pos)] != null)
return true;
return false; // replace this with working code
}
should be changed to something like:
private boolean hasLeft ( int pos )
{
if (storage.length > leftChild(pos) && storage[leftChild(pos)] != null)
return true;
return false; // replace this with working code
}
since you could be going out of bounds in your original code. The same logic applies to hasRight(). Additionally, you're also attempting to access storage, but you're never checking its length, ie you have storage[1], but there's not guarantee that you didn't pass 0 to your constructor. Hope that helps.

Creating an Array of Linked list

My program is meant to take a list of words and store each word under a letter reference in an array in ascending order. For example array of A-Z words apple, ape under a linked list under A referenced by 0, Zebra under Z referenced by 25. But when I use the standard first = new Node(word) I am not adding anything. I'm hopelessly lost.
import java.util.LinkedList;
public class ArrayLinkedList
{
/**
The Node class is used to implement the
linked list.
*/
private class Node
{
String value;
Node next;
/**
* Constructor
* #param val The element to store in the node
* #param n The reference to the successor node
*/
Node(String val, Node n)
{
value = val;
next = n;
}
Node(String val)
{
this(val, null);
}
}
private final int MAX = 26; // Number of nodes for letters
private Node first; // List head
private Node last; // Last element in the list
private LinkedList[] alpha; // Linked list of letter references
/**
* Constructor to construct empty array list
*/
public ArrayLinkedList()
{
first = null;
last = null;
alpha = new LinkedList[MAX];
for (int i = 0; i < MAX; i++)
{
alpha[i] = new LinkedList();
}
}
/**
* arrayIsEmpty method
* To check if a specified element is empty
*/
public boolean arrayIsEmpty(int index)
{
return (alpha[index].size() == 0);
}
/**
* The size method returns the length of the list
* #return The number of elements in the list
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count++;
p = p.next;
}
return count;
}
/**
* add method
* Adds the word to the first position in the linked list
*/
public void add(String e)
{
String word = e.toLowerCase(); // Put String to lowercase
char c = word.charAt(0); // to get first letter of string
int number = c - 'a'; // Index value of letter
// Find position of word and add it to list
if (arrayIsEmpty(number))
{
first = new Node(word);
first = last;
}
else
{
first = sort(first, word, number);
}
}
/**
* nodeSort method
* To sort lists
*/
private Node sort(Node node, String value, int number) {
if (node == null) // End of list
{
return getNode(value, number);
}
int comparison = node.value.compareTo(value);
if (comparison >= 0) // Or > 0 for stable sort.
{
Node newNode = getNode(value, number); // Insert in front.
newNode.next = node;
return newNode;
}
node.next = sort(node.next, value, number); // Insert in the rest.
return node;
}
private Node getNode(String value, int number)
{
return first.next;
}
/**
* get method
* to get each word value from the linked list and return it
* #return value
*/
public LinkedList get(int index)
{
return alpha[index];
}
public String toString()
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("Word and occurrence in ascending order\n\n");
Node p = first;
while (p != null)
{
sBuilder.append(p.value + "\n");
p = p.next;
}
return sBuilder.toString();
}
}
Is there a reason you are doing it this way.
I can think of an easier way: use Map which will map a character (e.g. "A") to a LinkedList of Words.

Java Hash Symbol Table Implementation

I built a symbol table using an array list filled with an object "pairs" that are singly-linked chains and hold a word and the number of times it occurs in a text file. I need to use this for the FrequencyCounter program that counts the number of words in a file. For some reason, I'm getting this error when running the the FrequencyCounter with the HashST:
Processed 1215985 words (19 sec; 19710 msec
Exception in thread "main" java.lang.NullPointerException
at HashST.hashIndex(HashST.java:60)
at HashST.get(HashST.java:105)
at FrequencyCounter.main(FrequencyCounter.java:112)
I have an idea that there's something wrong with my HashST and its not putting the pairs in the ArrayList like I wanted it to. Any suggestions on what is wrong with the implementation would be greatly appreciated.
Here is my code and the code for the FrequencyCounter:
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Iterator;
public class HashST<Key extends Comparable<Key>, Value> implements Iterable<Key> {
private ArrayList<Pair> chains;
private int numKeys;
private int numChains;
public class Pair
{
Key key;
Value value;
Pair(Key k, Value v)
{
key = k;
value = v;
}
Pair()
{}
Pair next;
}
/**
* Initialize an empty HashSt with a default of 64 empty chains.
*/
public HashST()
{
this(64);
}
/**
* Initialize an empty HashST with numChains emptychains.
* 387911 is a prime number about twice the number of distinct
* words in the leipzig1M.txt file.
*/
public HashST(int numChains)
{
this.numChains = numChains;
chains = new ArrayList<Pair>();
for(int i = 0; i < numChains; i++)
{
Pair p = new Pair(null, null);
chains.add(p);
}
}
/**
* compute the hash index for a key k if the number of
* chains is N
*/
private int hashIndex(Key k, int N)
{
return (k.hashCode() & 0x7fffffff) % N;
}
/**
* insert the Pair (k,v) into the appropriate chain and increment
* the number of keys counter or
* update the value for k if k is already in the hash table.
*
*/
public void put(Key k, Value v) {
int i = hashIndex(k, numChains);
Pair tmp = chains.get(i);
if(contains(k))
{
while(tmp.next != null)
{
if(tmp.key == k)
{
tmp.value = v;
return;
}
tmp = tmp.next;
}
}
else
{
Pair p = new Pair(k, v);
tmp.next = p;
numKeys ++;
}
}
/**
* return the value for key k if it is in the hash table
* or else return null if it is not.
*/
public Value get(Key k) {
int i = hashIndex(k, numChains);
Pair tmp = chains.get(i);
while(tmp.next != null)
{
if(tmp.key == k)
{
return tmp.value;
}
tmp = tmp.next;
}
return null;
}
/**
* remove the pair with key k if it is in the hash table
* otherwise no change.
*/
public void delete(Key k) {
if(contains(k))
{
return;
}
}
/**
* return true if the hash table contains a pair with key
* equal to k else return false
*/
public boolean contains(Key k) {
return (get(k) != null) ? true : false;
}
/**
* return the number of keys in the hash table
*/
public int size() {
return numKeys;
}
/**
* return a LinkedList<Key> containing the keys in the
* hash table
*/
public Iterable<Key> keys() {
LinkedList<Key> l = new LinkedList<Key>();
for(Pair p : chains)
{
while(p.next != null)
{
l.add(p.key);
p = p.next;
}
}
return l;
}
/**
* return an Iterator<Key> for the keys in the hash table
*/
public Iterator<Key> iterator() {
return keys().iterator();
}
}
And here is the Frequency Counter: http://algs4.cs.princeton.edu/31elementary/FrequencyCounter.java.html
According to your stack trace this would seem to be the line that threw a null pointer:
return (k.hashCode() & 0x7fffffff) % N;
So we have one object reference k, an integer constant, and a primitive N. Neither the constant nor the primitive can be null, the only thing being dereferenced here is k. So it looks like someone tried to get a value for a null k!

Categories