Question

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];
Was it helpful?

Solution 2

You are trying to create the array of Generic type,Please look at this post.

How to create a generic array in Java?

OTHER TIPS

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.

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;
    }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top