带对象的Java ArrayList
所以我有这类术语带对象的Java ArrayList,java,object,arraylist,Java,Object,Arraylist,所以我有这类术语 public class Term { private int coefficient ; private int exponent ; public Term(int coefficient, int exponent) { this.coefficient = coefficient ; this.exponent = exponent ; } public int getCo() { return coefficient ; } publi
public class Term {
private int coefficient ;
private int exponent ;
public Term(int coefficient, int exponent)
{
this.coefficient = coefficient ;
this.exponent = exponent ;
}
public int getCo()
{
return coefficient ;
}
public int getEx()
{
return exponent ;
}
}
我有一个叫做多项式的类,它用一个叫做delete的方法创建了一个term类型的arraylist,这个方法没有按我所希望的方式工作,我不明白为什么:
public class Polynomial{
public Polynomial()
{
poly = new ArrayList<>() ;
}
public void delete (int coeff, int expo)
{
for(int i = 0; i < poly.size(); i++)
{
System.out.println("**Delete Loop works") ; //This does not print
if( (poly.get(i).getCo() == coeff) && (poly.get(i).getEx() == expo) )
{
poly.remove(i) ;
removed = true ;
break ;
}
}
}
}
公共类多项式{
公共多项式()
{
poly=新的ArrayList();
}
公共作废删除(内部系数、内部博览会)
{
对于(int i=0;i
每次我运行delete方法时,它总是抛出一个异常,我不知道为什么??我使用的是来自文本文件的输入(输入工作正常),我想我使用的地方可能会出错:poly.get(I).getCo()==coeff
写得正确吗
谢谢你能提供的任何帮助 在
多项式
构造函数中,定义了poly=new ArrayList()代码>,它创建的ArrayList中没有一个对象
这意味着poly.size()=0
,这就是为什么它不会进入循环,您的syso语句也不会执行
每次我运行delete方法和
我不知道为什么
您可能有ConcurrentModificationException
。引发异常的原因是您正在迭代数组列表,同时删除一个元素。尝试改用Iteratoriterator
和iterator.remove()
方法
Iterator<Poly>iterator = arrayList.iterator();
while(iterator.hasNext())
{
Poly poly = iterator.next();
if( (poly.getCo() == coeff) && (poly.getEx() == expo) )
iterator.remove();
}
Iteratoriterator=arrayList.iterator();
while(iterator.hasNext())
{
Poly=iterator.next();
if((poly.getCo()==coeff)和&(poly.getEx()==expo))
iterator.remove();
}
例外情况是什么?我在哪里写的//这不会打印
如果我写的循环总是正确的,它甚至不会打印。奇怪的是,如果SOP没有打印,那就意味着poly arraylist是空的,没有任何东西可以从中删除。我想你的arraylist
是空的//Main Method
-1 OP明确表示他有一个例外。如果大小为0
,则没有理由发生异常。