填充LinkedList的ArrayList

时间:2016-10-19 21:47:41

标签: java arraylist linked-list indexoutofboundsexception

我一直在研究这个项目,它创建了一个由哈希结构和桶组成的一致数据结构。 每次我尝试添加新元素时都会遇到问题。 我得到一个IndexOutOfBoundsExeption 我知道当我创建一个特定大小的ArrayList时,它只保留内存但实际上并不包含任何元素。 如何填充此ArrayList,以便我可以在其中添加元素。

public ConcordanceDataStructure(int i) {

            this.size=fourKPrime(i);
            this.hashtable=new ArrayList<LinkedList<ConcordanceDataElement>(size);


        }

此方法出现问题:

public void add(String term, int lineNum){ 
        boolean noError;
        boolean hit = false;
        int pass, q, offset, ip;
        int pk = Math.abs(term.toLowerCase().hashCode()); // preprocess the key
        if (nodes<=getTableSize())// insert the node
        { 
            pass = 0;
            q = pk / getTableSize();
            offset = q;
            ip = pk % getTableSize();
            if(q%getTableSize() == 0)
                offset = 9967;
        }
        else
        {
            System.out.println("FULL");
            return;
        }
        while(pass < getTableSize())
        { 
            if(hashtable.get(ip) == null){  //PROBLEM IS HERE
                hit = true;
                break;
            }
            ip = (ip + offset)%getTableSize();
            pass = pass +1;
        }
        if(hit == true) // insert the node
        { 
            hashtable.add(ip, new LinkedList<ConcordanceDataElement>());

            hashtable.get(ip).add(new ConcordanceDataElement(term));
            hashtable.get(ip).get(hashtable.get(ip).size()).addPage(lineNum);
            nodes++;

        }

1 个答案:

答案 0 :(得分:0)

使用LinkedList而不是ArrayList<LinkedList>的数组:

[编辑以避免编译错误]

protected LinkedList<ConcordanceDataElement>[] hashtable;


public ConcordanceDataStructure(int i) {

   this.size=fourKPrime(i);
   @SuppressWarnings("unchecked")
   this.hashtable=new LinkedList[this.size];


}

protected int getTableSize() {
  return this.hashtable.length;
}

public void add(String term, int lineNum){ 
    boolean noError;
    boolean hit = false;
    int pass, q, offset, ip;
    int pk = Math.abs(term.toLowerCase().hashCode()); // preprocess the key
    if (nodes<=getTableSize())// insert the node
    { 
        pass = 0;
        q = pk / getTableSize();
        offset = q;
        ip = pk % getTableSize();
        if(q%getTableSize() == 0)
            offset = 9967;
    }
    else
    {
        System.out.println("FULL");
        return;
    }
    while(pass < getTableSize())
    { 
        if(hashtable[ip] == null){  // no more problems
            hit = true;
            break;
        }
        ip = (ip + offset)%getTableSize();
        pass = pass +1;
    }