【问题标题】:how to add string array elements to arraylist in java如何在java中将字符串数组元素添加到arraylist
【发布时间】:2017-01-11 08:35:04
【问题描述】:

如何将字符串数组元素添加到数组列表中?

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

    List<BudgetEntity> budgetEntityList = new ArrayList<>(20); 
    BudgetEntity budgetEntity = new BudgetEntity();

    String budgetID[] = request.getParameterValues("budgetID");

for(int i=0;   i < budgetID.length ;   i++) {

      for(int k=0;   k < budgetEntityList.size() ;   k++) {

          budgetEntity=  budgetEntityList.get(k);
      }

            budgetEntity.setTotal(Integer.valueOf(budgetID[i]));
        }

【问题讨论】:

  • 我在 java.util.ArrayList.get(来源不明)在 com.watanialivestock.contoller.BudgetSaveServlet.doPost(BudgetSaveServlet.java:75)
  • 请编辑您的问题,除此之外,请参阅How to Ask 写一个正确的问题。
  • 堆栈跟踪(尽管在注释中很难阅读)指的是 Budg‌​etSaveServlet.java 的第 75 行。那是哪条线?
  • 如前所述,通过编辑来改进您的问题。如果问异常的原因,那么在arraylist中添加字符串数组元素是什么关系?

标签: java indexoutofboundsexception


【解决方案1】:

当您执行budgetEntity= budgetEntityList.get(k); 时,您的budgetEntityList 为空

执行new ArrayList&lt;&gt;(capacity) 不会用 BudgetList 对象填充 ArrayList,它只会设置 ArrayList 的初始容量。

那么,你需要做的是:

 for(int k=0;   k < budgetEntityList.size() ;   k++) {
      budgetEntity = new BudgetEntity();
      budgetEntityList.add(budgetEntity);
  }

然后,设置您的 BudgetEntity 的总数

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多