数组索引超出范围

Par*_*wan 0 java arrays string indexoutofboundsexception

我想创建一个组合框,它在运行时从数据库中获取名称.所以我创建了一个空字符串数组,但它抛出了一个异常,即arrayindexoutofbound.我认为初始化有一个错误.....

            String s[]=new String[0];
            {
                 try
                {
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                  Connection con =DriverManager.getConnection("jdbc:odbc:project","sa","123456");
                  Statement stmt= con.createStatement();
                  ResultSet rs=stmt.executeQuery("SELECT Name FROM company");
                  i=0;
                  while(rs.next()) {        
                        s[i]=rs.getString(1);
                        i++;
                  }
                }
                catch(Exception ex)
                {
                    JOptionPane.showConfirmDialog(f,ex);
                }
                cb=new JComboBox(s);
            }
Run Code Online (Sandbox Code Playgroud)

NIN*_*OOP 10

数组是一个容器对象,它包含固定数量的单个类型的值.创建数组时,将建立数组的长度.创建后,其长度是固定的.您正在创建一个数组来保存0个元素.

String s[]=new String[0]; //<< intialized with length 0
Run Code Online (Sandbox Code Playgroud)

ArrayindexoutOfBoundsException当你试图访问它的第一个元素时它会抛出s[0].

抛出以指示已使用非法索引访问数组.索引为负数或大于或等于数组的大小.

调整数组的大小0,因此在访问索引时会抛出异常0.

下面是一个用于理解的数组的基本图表.

在此输入图像描述

它是长度的阵列10,从索引09.

由于您在声明数组本身时不知道数据结构需要存储的元素数量.在你的情况下最好使用动态集合,可能是List的任何一个实现,比如ArrayList.

List<String> s = new ArrayList<String>();
while(rs.next())
{
   s.add(rs.getString("NAME")); // using column name instead of index "1" here
}
Run Code Online (Sandbox Code Playgroud)

推荐阅读:

  1. Oracle关于Java数组的教程
  2. 列表与阵列 - 何时使用什么