生产者 - 消费者模型应用程序中的ArrayIndexOutOfBoundsException [英] ArrayIndexOutOfBoundsException in a producer-consumer model app

查看:97
本文介绍了生产者 - 消费者模型应用程序中的ArrayIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在使用一个简单而简单的逻辑工作java应用程序,但我遇到了一个明显的小问题 - ArrayIndexOutOfBoundsException。我无法解决这个问题。任何帮助都将为我节省宝贵的时间,并对回复者深表敬意。



谢谢



Amer Rehman < br $> b $ b

Hi

I am working on a java app with a simple and plain logic but I'm stuck with an apparently minor issue - ArrayIndexOutOfBoundsException. I am unable to tackle this one. Any help will save me valueable time with deep regards for the replier.

Thanks

Amer Rehman

/**
import java.util.*; 
public class PageWriter {
    
    private static Vector vecImages = new Vector();
    
    public static void main(String[] args) {
    	
    	int n = 0;
    	
    	while(n < 1500){
    		
    		n++;
    		
    		vecImages.addElement(new Integer(n));
    		
    		int vecSize = vecImages.size();
    		
    		if(vecSize == 100){
    			
    			try {
    				
    				writePages();
    
				}
				catch (ArrayIndexOutOfBoundsException ex) {
					
					ex.printStackTrace();
				}
    			
    		}
    	}
    	
    }
    public static void writePages(){
    	
    	Random rand = new Random(System.currentTimeMillis());
    	int endIndex = 60 + rand.nextInt( 10 );
    	
    	for (int i = 0; i < endIndex; i++){
    		
    		vecImages.removeElementAt(i);
    	}
    	
    	System.out.println ("Entries written and removed:" + endIndex);
    }
}

推荐答案

引用:

for(int i = 0; i< endIndex; i ++){



vecImages.removeElementAt(i);

}

for (int i = 0; i < endIndex; i++){

vecImages.removeElementAt(i);
}



这不起作用,因为你正在删除项目,因此当你使用原始结束作为循环限制时,向量会缩小。



有一些解决方案,例如

您可以删除元素'向后',即:


This doesn't work because you are removing items, hence the vector shrinks while you are using the original end as loop limit.

There are some solutions, for instance
You may remove elements 'backwards', that is:

for (int i = endIndex-1; i >= 0; i--){

            vecImages.removeElementAt(i);
        }





或者您可以随时删除第一个条目:





or you may always remove the first entry:

for (int i = 0; i < endIndex; i++){

            vecImages.removeElementAt(0);
        }


这篇关于生产者 - 消费者模型应用程序中的ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆