简体   繁体   中英

Error while adding user designed object in arraylist

I have to make a polynomial class Polynom that would extend a monomial class Monom . The objects in Monom can be both int or double so I thought I would use generics.

I tried making the Polynom by adding the Monom into an ArrayList . All fine, but I keep getting an error at p1.add(m1); :

Multiple markers at this line
    - Syntax error, insert "Identifier (" to complete 
     MethodHeaderName
    - Syntax error, insert ")" to complete MethodDeclaration
    - Syntax error, insert "SimpleName" to complete 
     QualifiedName
    - Syntax error on token ".", @ expected after this token

I searched everywhere and this should be the right syntax.

import java.util.*;

public class Polinom {

    Integer grad, coef = new Integer(0);
    Monom<Integer> m1= new Monom<Integer>(grad, coef);
    ArrayList<Monom<Integer>> p1 = new ArrayList<Monom<Integer>>();
    ArrayList<Monom<Integer>> p2 = new ArrayList<Monom<Integer>>();

    p1.add(m1);

}

This is how the Monom class looks like:

public class Monom<T> {

    private T grad, coef;

    public Monom (T grad, T coef) {
        this.grad = grad;
        this.coef = coef;
    }
    public T getGrad() {
        return this.grad;
    }
    public T getCoef() {
        return this.coef;
    }

}

The line p1.add(m1); should be inside a method. For example

public void doSomething() {
    p1.add(m1);
}

Have your Class polinom like this.

import java.util.*;

public class Polinom {

  Integer grad, coef = new Integer(0);
  Monom<Integer> m1= new Monom<Integer>(grad, coef);
  ArrayList<Monom<Integer>> p1 = new ArrayList<Monom<Integer>>();
  ArrayList<Monom<Integer>> p2 = new ArrayList<Monom<Integer>>();
  public void anyMethod()
  {
   p1.add(m1);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM