Java在数组中编写的方法中实现ArrayList
已编辑 我编写了一个方法,使用数组将术语对象添加到多项式类中存储术语对象,现在我想使用ArrayList而不是array。我使用get()和add()将数组更改为arraylist,但程序不再给出正确答案。以下是我更改后的方法:Java在数组中编写的方法中实现ArrayList,java,arrays,arraylist,Java,Arrays,Arraylist,已编辑 我编写了一个方法,使用数组将术语对象添加到多项式类中存储术语对象,现在我想使用ArrayList而不是array。我使用get()和add()将数组更改为arraylist,但程序不再给出正确答案。以下是我更改后的方法: public void addTerm(int c, int e) { for (int i = 0; i < terms.size(); i++) { // if term with exponent not exist
public void addTerm(int c, int e) {
for (int i = 0; i < terms.size(); i++) {
// if term with exponent not exist
if (terms.get(i) == null) {
// no coefficients of zero are stored
if (c == 0) {
return;
}
terms.add(new Term(c, e) );
return;
}
// if term with exponent already exist
if (terms.get(i).getExponent() == e) {
int coe = terms.get(i).getCoefficient();
int newCoe = coe + c;
// no coefficients of zero are store
if (newCoe == 0) {
terms.add(null);
return;
}
terms.get(i).setCoefficient(newCoe);
return;
}
}
}
public void addTerm(int c,int e){
对于(int i=0;i
以下是原始代码:
public void addTerm(int c, int e) {
for (int i = 0; i < termSize; i++) {
// if term with exponent not exist
if (terms[i] == null) {
// no coefficients of zero are store
if (c == 0) {
return;
}
terms[i] = new Term(c, e);
return;
}
// if term with exponent already exist
if (terms[i].getExponent() == e) {
int coe = terms[i].getCoefficient();
int newCoe = coe + c;
// no coefficients of zero are store
if (newCoe == 0) {
terms[i] = null;
return;
}
terms[i].setCoefficient(newCoe);
return;
}
}
}
public void addTerm(int c,int e){
对于(int i=0;i
这将在指定位置添加对象(如果有[4,5,6],并在位置2添加元素9,则得到[4,5,9,6])
我想你要做的是在这个位置设置值
terms.set(i,new Term(c, e) );
编辑:
您还确保terms.size()返回正确的值吗
您不应该只是将数组代码转换为列表代码。他们完全不同。如果有固定数量的对象并且事先知道对象的大小,则应使用数组。如果对象数量发生变化/不合适,则应使用列表。数组为每个对象设置了位置,而列表通常只在末尾添加
编辑问题后进行编辑:
首先,如果你编辑了你的问题,请在你原来的帖子末尾添加修改。不要改变你原来的问题(这会让以后阅读你文章的人感到困惑)
其次,如果上面的代码是您的新代码,则可能是term.size()返回的值与termSize不同。原因是在您的阵列版本中,阵列的大小从未更改(其大小是固定的)。
鉴于在列表版本中添加(新术语(c,e));将列表大小增加1
此外,我们不知道您的数组/列表是如何初始化的。如果你这样做
Term[] terms = new Term[100];
数组大小为100,但如果对列表进行常规初始化
ArrayList<Term> terms = new ArrayList<>();
arraylistterms=newarraylist();
它的大小是0,您必须添加100个空对象才能获得相同的结果
for(int i=0; i<100; i++){
terms.add(null);
}
for(int i=0;i请详细说明“程序不再工作”。您可能希望通过朗读帮助您提出一个问题,以获得有用的答案。我仍然没有得到正确的答案。为什么您认为term.size()可能无法返回正确的值?
for(int i=0; i<100; i++){
terms.add(null);
}