2015-03-19 85 views
-1

我有一個問題。我知道如果我的堆棧已滿,我必須分配一個雙倍大小的新堆棧。我已經嘗試使用臨時堆棧,但在編譯期間,我在55行看到一個錯誤。錯誤是「無法在數組類型E []」上調用push(E)。我不知道爲什麼我不能這樣做。Java堆棧無法在陣列類型E上調用推送(E)[]

package stack; 

import exception.EmptyStackException; 

import exception.FullStackException; 

public class ArrayStack<E> implements Stack<E>{ 

protected int capacity; 
protected static final int CAPACITY = 1000; 
protected E S[]; 
protected int top = -1; 

@SuppressWarnings("unchecked") 
public ArrayStack(int capacity){ 
    this.capacity = capacity; 
    this.S = (E[]) new Object[this.capacity]; 
} 

public ArrayStack(){ 
    this(CAPACITY); 
} 

@Override 
public int size() { 
    return top+1; 
} 

@Override 
public boolean isEmpety() { 
    return (this.top < 0); 
} 

@Override 
public E top() throws EmptyStackException { 
    if(isEmpety()) 
     throw new EmptyStackException("Stack Vuoto."); 
    return this.S[top]; 
} 

@Override 
public void push(E element) throws FullStackException, EmptyStackException { 
    if(size() == capacity){ 
     this.tempStack(); 

    } 
    //throw new FullStackException("Stack Pieno."); 
    this.S[++top] = element; 
} 

private void tempStack(){ 
    E tempS[] = (E[]) new Object[this.capacity]; 
    E tempEl; 
    while(isEmpety()){ 
     tempEl = this.pop(); 
     tempS.push(this.pop()); 
    } 
    this.capacity += this.capacity; 
    this.S = null; 
    this.S = (E[]) new Object[this.capacity]; 
} 

public void union(Stack<E> s){ 

} 

@Override 
public E pop() throws EmptyStackException { 
    E element; 
    if(isEmpety()) 
     throw new EmptyStackException("Stack Vuoto."); 
    element = S[top]; 
    this.S[top--] = null; 
    return element; 
} 

} 
+2

我們不知道,爲什麼你想調用不存在的方法''array'對象push' 。 – Andremoniy 2015-03-19 10:07:20

回答

0

tempS不是Stack,所以你不能調用Stack方法這個變量。

您的tempStack方法應該做的事情可能是創建一個容量較大的陣列,將this.S複製到新陣列並將該陣列分配到this.S

+0

if(size()== capacity){ \t \t \t this.capacity + = this.capacity; \t \t \t E tempS [] =(E [])new Object [this.capacity]; \t \t \t tempS = this.S; \t \t \t this.S = null; \t \t \t this.S =(E [])new Object [this.capacity]; \t \t \t this.S = tempS; \t \t \t \t \t}當我在tempStack複製this.S大小保持老大小 – 2015-03-19 10:38:25

+0

@MarcoFerraioli'臨時工= this.S'不this.S複製到臨時工,它只是複製了參考。您應該使用Arrays.copyOf將原始數組的元素複製到目標數組。 – Eran 2015-03-19 10:41:16

0
E tempS[] = (E[]) new Object[this.capacity]; 

臨時工是一個數組不就可以了堆棧所以你不能調用push方法