2013-03-31 3 views
0

이렇게 JavaBean 클래스를 생성했습니다.빈을 ArrayList에 추가 할 수 없습니다.

package beans; 

public class Invoice { 
    private String companyName; 
    private double price; 

    public String getCompanyName() { 
     return companyName; 
    } 

    public void setCompanyName(String companyName) { 
     this.companyName = companyName; 
    } 

    public double getPrice() { 
     return price; 
    } 

    public void setPrice(double price) { 
     this.price = price; 
    } 

} 

그런 다음 HTML 파일의 매개 변수를 가져 와서 빈을 작성한 서블릿을 만들었습니다. 빈을 ArrayList에 추가하려고합니다.

protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 

     String companyName = request.getParameter("txtCompany"); 
     double price = Double.parseDouble(request.getParameter("txtPrice")); 

     ArrayList<Invoice> list = (ArrayList<Invoice>) new ArrayList(); 
     Invoice r = new Invoice(); 
     r.setCompanyName(companyName); 

     list.add(r.getCompanyName()); 
     r.setPrice(price); 

    } 

} 

하지만 에이 오류가 내가 잘못 될 수도입니다

The method add(Invoice) in the type ArrayList<Invoice> is not applicable for the arguments (String) 

을 .add는 무엇입니까?

답변

0

코드가 잘못 관리되고 잘못되었습니다.

  1. 선언 및 지정. ArrayList<Invoice> list = (ArrayList<Invoice>) new ArrayList();이 있습니다. 코드가 작동하는 동안 은 왜 할당 중에 제너릭을 사용하지 않으며 캐스트를 수행하는지 알 수 없습니다. 다음에는 일반적으로 꽉 끼는 연결을 피하기 위해 은 인터페이스로 변수를 선언하지만 구체적인 구현이 아닙니다. 수정하면 다음 줄을보실 수 있습니다 : List<Invoice> list = new ArrayList<Invoice>();.
  2. 컬렉션 채우기. 의 인스턴스가 클래스으로 표시되도록 선언 했으므로 Invoice에서 상속받은 Invoice 개의 개체와 개체 만 개를 추가 할 수 있습니다. 끝으로, list.add(r.getCompanyName()); 줄에는 Invoice을 확장하지 않는 문자열이나 그 하위 클래스를 추가하려고합니다. 그래서 객체를 추가하십시오 : list.add(r) 그리고 괜찮을 것입니다.
0

ArrayList < Invoice> list = (ArrayList < Invoice>) 새 ArrayList(); 인보이스 r = 새 인보이스(); r. setCompanyName (companyName); r. setPrice (price); 목록 add (r)}} invoce 객체 만 추가해야합니다 ... 문자열을 직접 삽입하려고합니다 ...

관련 문제