Java通用堆栈错误
所以我用Java创建了一个DoubleQueue。。这是针对我的数据结构和算法类的,我们试图展示DoubleQueue可以用来实现堆栈和队列。下面是它的工作原理: 它使用一个数组来存储项目,头部指向数组中的前部项目,尾部指向数组的后部项目。阵列是圆形的,当容量达到90%时,它会扩展。现在,我认为这一扩张引起了轩然大波。当我向堆栈中添加一组整数,然后将它们全部删除时,它们以相反的顺序显示良好。但是,我正试图通过按下string.charAt来反转字符串,然后弹出所有字符并打印它们。对于长度足够短且不需要扩展的字符串,这种方法非常有效。然而,一旦需要扩展,我就会得到一个奇怪的输出,其中包括混乱的字符(顺序不正确,缺少字符)以及空值 我认为这与我如何施展阵列有关:Java通用堆栈错误,java,generics,data-structures,Java,Generics,Data Structures,所以我用Java创建了一个DoubleQueue。。这是针对我的数据结构和算法类的,我们试图展示DoubleQueue可以用来实现堆栈和队列。下面是它的工作原理: 它使用一个数组来存储项目,头部指向数组中的前部项目,尾部指向数组的后部项目。阵列是圆形的,当容量达到90%时,它会扩展。现在,我认为这一扩张引起了轩然大波。当我向堆栈中添加一组整数,然后将它们全部删除时,它们以相反的顺序显示良好。但是,我正试图通过按下string.charAt来反转字符串,然后弹出所有字符并打印它们。对于长度足够短且
/**
* Expands the capacity of the storage array that holds the collection of items
* within the DoubleQueue *** only if expansion is needed ***
* @return True if the array was expanded; False otherwise
*/
@SuppressWarnings({"unchecked"})
public boolean expandArray() {
// First, see if need to expand
if( (double) size / storage.length >= CAPACITY_EXPAND ) {
// Create a temporary pointer to the storage array
E[] temp = storage;
// First out what type of expansion we're doing and create a new, larger array
if( expansionRule == EXPANSION_DOUBLE )
storage = ( E[] )new Object[ 2 * temp.length ];
else
storage = ( E[] )new Object[ temp.length + INCREASE_CONSTANT ];
int i = 0; // Counter for storage
int j = tail; // Counter for temp
// Copy temp to storage
while( j != head ) {
storage[ i ] = temp[ j ];
if( j == temp.length - 1 ) j = 0; // If we have to wrap around the array
else j++;
i++;
}
storage[ i ] = temp[ j ];
return true;
}
return false;
}
以下是全部代码:
public class DoubleQueue<E> {
/** CONSTANTS **/
private final int INCREASE_CONSTANT = 10; // The amount to increase by if expansion rule is increase by constant
private final double CAPACITY_EXPAND = 0.9; // The size:capacity ratio at which the storage should be expanded
public static final char EXPANSION_DOUBLE = 'd'; // Parameter for expansionRule()
public static final char EXPANSION_CONSTANT = 'c'; // Parameter for expansionRule()
/** VARIABLES **/
private char expansionRule; // Stores the current expansion rule
private int head; // Keeps track of the index of the first element
private int tail; // Keeps track of the index of the last element
private int size; // Keeps track of the number of items in storage
private E storage[]; // Holds the collection of items
/** CONSTRUCTORS **/
/**
* Creates an empty DoubleQueue with a given capacity. Initializes variables
* and sets the default expansion rule.
* @param capacity The initial capacity of the DoubleQueue
*/
@SuppressWarnings({ "unchecked" })
public DoubleQueue( int capacity ) {
size = 0;
head = -1;
tail = -1;
storage = ( E[] )new Object[ capacity ];
setExpansionRule( EXPANSION_DOUBLE );
}
/**
* Creates an empty DoubleQueue of initial capacity 10.
*/
public DoubleQueue() {
this( 10 );
}
/** METHODS **/
/**
* Checks to see if the DoubleQueue is currently empty
* @return True if the DoubleQueue is empty; False otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Adds an item at the beginning of the DoubleQueue
* @param item The item to be added to the DoubleQueue
* @return True if the item was successfully added
*/
public boolean addFirst( E item ) {
// First, perform expansion if neccessary
expandArray();
// Put the head and tail pointers in the right spots
if( isEmpty() ) {
head = 0;
tail = 0;
} else if( head == storage.length - 1 ) head = 0;
else head++;
// Add the item
storage[ head ] = item;
// Increment the size
size++;
return true;
}
/**
* Adds an item at the end of the DoubleQueue
* @param item The item to be added to the DoubleQueue
* @return True if the item was successfully added
*/
public boolean addLast( E item ) {
// First, perform expansion if neccessary
expandArray();
// Put the head and tail pointers in the right place
if( isEmpty() ) {
head = 0;
tail = 0;
} else if( tail == 0 ) tail = storage.length - 1;
else tail--;
// Add the item
storage[ tail ] = item;
// Increment the size
size++;
return true;
}
/**
* Expands the capacity of the storage array that holds the collection of items
* within the DoubleQueue *** only if expansion is needed ***
* @return True if the array was expanded; False otherwise
*/
@SuppressWarnings({"unchecked"})
public boolean expandArray() {
// First, see if need to expand
if( (double) size / storage.length >= CAPACITY_EXPAND ) {
// Create a temporary pointer to the storage array
E[] temp = storage;
// First out what type of expansion we're doing and create a new, larger array
if( expansionRule == EXPANSION_DOUBLE )
storage = ( E[] )new Object[ 2 * temp.length ];
else
storage = ( E[] )new Object[ temp.length + INCREASE_CONSTANT ];
int i = 0; // Counter for storage
int j = tail; // Counter for temp
// Copy temp to storage
while( j != head ) {
storage[ i ] = temp[ j ];
if( j == temp.length - 1 ) j = 0; // If we have to wrap around the array
else j++;
i++;
}
storage[ i ] = temp[ j ];
return true;
}
return false;
}
/**
* Gets the element at the front of the DoubleQueue & removes it
* @throws EmptyDoubleQueueException if the queue is empty and there is no item to remove
* @return The item at the front of the DoubleQueue
*/
public E removeFirst() throws EmptyDoubleQueueException {
// If the DoubleQueue is empty we obviously can't get an element from it..
if( size == 0 ) throw new EmptyDoubleQueueException();
// Create a temporary record of the item and remove it from storage
E temp = storage[ head ];
storage[ head ] = null;
size--; // Decrease the size of the DoubleQueue
if( size == 0 ) { // If we're taking the last element
head = -1;
tail = -1;
} else if ( head == 0 ) head = storage.length - 1; // Wrap around the array
else head--;
return temp;
}
/**
* Gets the item at the back of the DoubleQueue & removes it
* @throws EmptyDoubleQueueException if the queue is empty and there is no item to return
* @return The item at the back of the doubleQueue
*/
public E removeLast() throws EmptyDoubleQueueException {
// If the DoubleQueue is empty we obviously can't get an element from it..
if( size == 0 ) throw new EmptyDoubleQueueException();
// Create a temporary record of the item and remove it from storage
E temp = storage[ tail ];
storage[ tail ] = null;
size--; // Decrease the size of the DoubleQueue
if( size == 0 ) { // If we're taking the last element
head = -1;
tail = -1;
} else if ( tail == storage.length - 1 ) tail = 0; // Wrap around the array
else tail++;
return temp;
}
/**
* Gets the item at the front of the DoubleQueue
* @return The item at the front of the DoubleQueue; null if list is empty
*/
public E peekFirst() {
if( size == 0 ) return null; // Nothing to return
return storage[ head ];
}
/**
* Gets the item at the back of the DoubleQueue
* @return The item at the back of the DoubleQueue; null if list is empty
*/
public E peekLast() {
if( size == 0 ) return null; // Nothing to return
return storage[ tail ];
}
/**
* Trims the size of the underlying collection to the exact number of items within
* the collection
*/
@SuppressWarnings({"unchecked"})
public void truncate() {
E[] temp = storage; // Create a temporary pointer to storage
storage = ( E[] )new Object[ storage.length ]; // Create a new storage array that is the size of the # of elements in storage
int i = 0; // Pointer to iterate storage
int j = 0; // Pointer to iterate temp
// Copy values from temp to storage
while( j != head ) {
storage[ i ] = temp[ j ];
i++;
if( j == temp.length - 1 ) j = 0; // Wrap around array
else j++;
}
}
/**
* Sets the type of expansion to be used when the underlying array nears capacity
* @param rule The type of expansion to be used in the future
* @throws InvalidInputException when the input provided does not correspond to an expansion type
* @return True if the expansion rule was set successfully
*/
public boolean setExpansionRule( char rule ) {
// Check to make sure the rule provided was valid
if( rule != EXPANSION_CONSTANT && rule != EXPANSION_DOUBLE )
throw new InvalidInputException();
// Set the rule
expansionRule = rule;
return true;
}
/**
* Returns the current capacity of the array that holds the collection of
* items currently in the DoubleQueue. This method is used for testing
* purposes only and WOULD NOT BE INCLUDED in a public release of DoubleQueue.
* @return The capcity of the storage array
*/
public int getCapacity() {
return storage.length;
}
/**
* Gets the number of elements currently in the DoubleQueue
* @return The number of elements currently in the DoubleQueue
*/
public int getSize() {
return size;
}
}
公共类双队列{
/**常数**/
private final int INCREASE_CONSTANT=10;//如果扩展规则是按常量递增,则递增的量
private final double CAPACITY_EXPAND=0.9;//应扩展存储的大小与容量之比
public static final char EXPANSION_DOUBLE='d';//expansionRule()的参数
public static final char EXPANSION_常量='c';//expansionRule()的参数
/**变数**/
private char expansionRule;//存储当前扩展规则
private int head;//跟踪第一个元素的索引
private int tail;//跟踪最后一个元素的索引
private int size;//跟踪存储中的项目数
私有E存储[];//保存项的集合
/**建设者**/
/**
*创建具有给定容量的空双队列。初始化变量
*并设置默认的扩展规则。
*@param capacity双队列的初始容量
*/
@SuppressWarnings({“unchecked”})
公共双队列(整数容量){
尺寸=0;
水头=-1;
尾=-1;
存储=(E[])新对象[容量];
setExpansionRule(扩展双精度);
}
/**
*创建初始容量为10的空双队列。
*/
公共双队列(){
这(10);
}
/**方法**/
/**
*检查DoubleQueue当前是否为空
*@如果DoubleQueue为空,则返回True;否则返回False
*/
公共布尔值为空(){
返回大小==0;
}
/**
*在DoubleQueue的开头添加项目
*@param item要添加到DoubleQueue的项
*@如果项目已成功添加,则返回True
*/
公共布尔addFirst(E项){
//首先,必要时进行扩展
expandArray();
//将头部和尾部指针放在正确的位置
if(isEmpty()){
水头=0;
尾=0;
}如果(head==storage.length-1)head=0,则为else;
else head++;
//添加项目
存储[头]=项目;
//增大尺寸
大小++;
返回true;
}
/**
*在DoubleQueue的末尾添加一个项
*@param item要添加到DoubleQueue的项
*@如果项目已成功添加,则返回True
*/
公共布尔addLast(E项){
//首先,必要时进行扩展
expandArray();
//将头部和尾部指针放在正确的位置
if(isEmpty()){
水头=0;
尾=0;
}如果(tail==0)tail=storage.length-1,则为else;
否则尾巴--;
//添加项目
储存[尾]=项目;
//增大尺寸
大小++;
返回true;
}
/**
*扩展包含项集合的存储阵列的容量
*仅当需要扩展时,在DoubleQueue***内***
*@如果数组已展开,则返回True;否则返回False
*/
@SuppressWarnings({“unchecked”})
公共布尔数组(){
//首先,看看是否需要扩展
如果((双倍)大小/storage.length>=容量\u扩展){
//创建指向存储阵列的临时指针
E[]温度=储存;
//首先确定我们正在进行的扩展类型,并创建一个新的、更大的阵列
if(expansionRule==EXPANSION\u DOUBLE)
存储=(E[])新对象[2*temp.length];
其他的
存储=(E[])新对象[温度长度+增加常数];
int i=0;//用于存储的计数器
int j=tail;//温度计数器
//将温度复制到存储器
while(j!=头){
储存量[i]=温度[j];
如果(j==temp.length-1)j=0;//如果我们必须环绕数组
else-j++;
i++;
}
储存量[i]=温度[j];
返回true;
}
返回false;
}
/**
*获取DoubleQueue前面的元素并将其删除
*@如果队列为空且没有要删除的项目,则会引发EmptyDoubleQueueException
*@返回双队列前面的项目
*/
public E removeFirst()引发EmptyDoubleQueueException{
//如果DoubleQueue为空,我们显然无法从中获取元素。。
如果(size==0)抛出新的EmptyDoubleQueueException();
//创建项目的临时记录并将其从存储器中删除
E温度=存储[头];
存储[头]=空;
大小--;//减小双队列的大小
如果(size==0){//如果我们使用最后一个元素
水头=-1;
尾=-1;
}else if(head==0)head=storage.length-1;//环绕数组
否则头——;
返回温度;
}
/**
*获取DoubleQueue后面的项并将其删除
*如果队列为空且没有要返回的项目,则@throws EmptyDoubleQueueException
*@返回双队列后面的项目
*/
public E removeLast()引发EmptyDoubleQueueException{
//如果DoubleQueue为空,我们显然无法从中获取元素。。
如果(size==0)抛出新的EmptyDoubleQueueException();
//创建项目的临时记录并将其从存储器中删除
E温度=存储[尾部];
存储[tail]=n
public class Driver {
public static void main( String[] args ) {
// First, check the isEmpty() method
System.out.println( "Check isEmpty() method:" );
DoubleQueue<Integer> dq = new DoubleQueue<Integer>();
if( dq.isEmpty() ) System.out.println( "isEmpty() method returns true when DoubleQueue is empty." );
else System.out.println( "ERROR: isEmpty() method returns false when DoubleQueue is empty." );
// Add something and check the isEmpty() method again
dq.addFirst( 1 );
if( dq.isEmpty() ) System.out.println( "ERROR: isEmpty() method returns true when DoubleQueue is not empty." );
else System.out.println( "isEmpty() method returns false when DoubleQueue is not empty." );
System.out.println();
// Test expansion using default expansion ( double )
System.out.println( "Check expansion by doubling (should double in capacity when the 10th element is added and again when the 19th element is added):" );
dq = new DoubleQueue<Integer>();
System.out.println( "Capacity before adding elements: " + dq.getCapacity() );
for( int i = 1; i <= 20; i++ ) {
dq.addFirst( i );
System.out.println( "Added element #" + i + ". Capacity: " + dq.getCapacity() + "." );
}
// Test expansion using constant expansion
System.out.println();
System.out.println( "Check expansion by constant (should add ten to capacity when the 10th and 19th elements are added)." );
dq = new DoubleQueue<Integer>();
dq.setExpansionRule( DoubleQueue.EXPANSION_CONSTANT );
System.out.println( "Capacity before adding elements: " + dq.getCapacity() );
for( int i = 1; i <= 20; i++ ) {
dq.addFirst( i );
System.out.println( "Added element #" + i + ". Capacity: " + dq.getCapacity() + ". " );
}
// Test functionality as a STACK
DoubleQueue<Character> stack = new DoubleQueue<Character>();
String toBeReversed = "reht olleh";
System.out.println();
System.out.println( "String to be reversed: " + toBeReversed );
// Add string to be reversed letter by letter into strck
for( int i = 0; i < toBeReversed.length(); i++ ) {
char j = toBeReversed.charAt( i );
stack.addLast( j );
System.out.println( "Added letter " + j );
}
System.out.println( stack.getCapacity() );
System.out.println( stack.getSize() );
// Print stack
while( !stack.isEmpty() ) {
try {
System.out.print( stack.removeLast() );
} catch( EmptyDoubleQueueException e ) {
}
}
/**
// This first bit tests the DoubleQueue as a stack, to reverse a strign
DoubleQueue<Character> dq1 = new DoubleQueue<Character>();
String toBeReversed = "hello";
for( int i = 0; i < toBeReversed.length(); i++ ) {
dq1.addLast( toBeReversed.charAt( i ) );
}
while( !dq1.isEmpty() ) {
try {
System.out.print( dq1.removeFirst() );
} catch( EmptyDoubleQueueException e ) {
// Do nothing
}
}**/
}
}