2013-08-08 1 views
0

배열 목록 크기를 30으로 초기화 할 때 왜 0입니까?배열 목록 크기를 30으로 초기화 할 때 왜 0입니까?

나는 addRecord()가 호출 될 때 java.lang.IndexOutOfBoundsException: Index: 1, Size: 0을 얻을

(참고 : JSP 나던 도움말에서 setInitialValues를 호출.)
(참고 : ShootRecord도 구현 직렬화)

서블릿 procesRequest 방법

 protected void processRequest(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 

    PrintWriter pw = resp.getWriter(); 
    String address = null; 
    HttpSession session = req.getSession(); 

    ShootMeet meetBean = (ShootMeet)session.getAttribute("shootmeetbean"); 

    if(meetBean == null){ 
     pw.print("initialising meet \n"); 
     meetBean = new ShootMeet(); 
     meetBean.setInitialValues(30); 
    } 


    ShootRecord recordSent = (ShootRecord)session.getAttribute("shootrecordbean"); 
    if(recordSent == null){ 
     recordSent = new ShootRecord(); 
    } 

// **record sent created here** 

try{   meetBean.addRecord(recordSent); 
} ... 
} 
// doGet and doPost call processRequest 

슈트 메이 트

public class ShootMeet implements Serializable{ 

    private ArrayList<ShootRecord> listOfRecords; 
    private String date; 
    private int numTargets; 

    public ShootMeet(){} 

    public void setInitialValues(int numTarg){ 

     numTargets = numTarg; 
     listOfRecords = new ArrayList<ShootRecord>(numTargets); 


    } 

    public void addRecord(ShootRecord s){ 

     if(listOfRecords.size() == 0){ 
     System.out.println("size of list of records is zero before adding record"); 
     } 
     listOfRecords.add(s.targetNumber, s); 

    } 
    //...other setters/getters 
} 

index.jsp를

<%@page import="servlet.ShootRecord"%> 
<%@page import="servlet.ShootRecordMap"%> 

<%@ page contentType="text/html" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 


<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<jsp:useBean id="shootmeetbean" class="servlet.ShootMeet" scope = "session"/> 
    <%--<jsp:setProperty name = "shootmeetbean" property = "initialValues" value = "1"/> 
</jsp:useBean>--%> 
<jsp:useBean id="shootrecordbean" class="servlet.ShootRecord" scope = "session"/> 


<html> 
    // ... jstl tags 
</html> 

답변

1

나는 혼란 목록 목록 크기와 용량, ArrayLists의와 배열의 기능이었다.

more detailed answer

사이즈리스트의 원소의 개수이고; 용량은 목록이 내부 구조를 재 할당하지 않고 수용 할 수있는 요소의 수입니다. 새 ArrayList (10)를 호출하면 크기가 아닌 목록의 초기 용량이 설정됩니다. 즉,이 방식으로 구성하면 배열 목록이 비어있는 상태로 시작됩니다.
0
Here 
    may be u r trying to add value in List at Index 1 when the u r Array List Size is Zero. 

    listOfRecords.add(1, s); 
    The above statement will throw Exception if the listOfRecords.size()==0; 
    So try to add values in List from Index 0; 
    There is different between Capacity and Size.Capacity is the how many elements u can add in u r list and it gets incremented and size is the how many elements u r list currently poses. 
So if the array list size is zero u cant start adding elements from Index 1. 
관련 문제