Reputation: 1238
So I have this class of terms
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 ;
}
}
And I have a class called Polynomial that creates an arraylist of type term with a method called delete that isn't working the way I'd like it to and I can't figure out why:
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 ;
}
}
}
}
It keeps throwing an exception every time I run the delete method and I'm not sure why?? I am using input from a text file (and the input is working fine), I think it might be going wrong where I use : poly.get(i).getCo() == coeff
is that properly written?
Thanks for any help you can provide!
Upvotes: 0
Views: 171
Reputation: 15428
It keeps throwing an exception every time I run the delete method and I'm not sure why??
You are probably having ConcurrentModificationException
. The exception is thrown because you are iterating over the array list and removing an element at the same time. Try using Iterator<T>iterator
instead and iterator.remove()
method.
Iterator<Poly>iterator = arrayList.iterator();
while(iterator.hasNext())
{
Poly poly = iterator.next();
if( (poly.getCo() == coeff) && (poly.getEx() == expo) )
iterator.remove();
}
Upvotes: 0
Reputation: 10497
In your Polynomial
constructor, you have defined poly = new ArrayList<>() ;
which creates ArrayList with not a single object in it.
That means poly.size() = 0
that's why it will not enter in loop and your syso statement will not executed.
Upvotes: 1