黎明前的黑暗是最难挨 2013-10-03 07:35 采纳率: 0%
浏览 964
已结题

Java编程中的初始化问题

为啥初始化字符串数组要放在无参构造函数中?放在外面时,就会报数组越界异常?代码如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;

import com.bdqn.hibernate.model.Student;

public class Session {
//模拟配置文件
String tableName="_Student";
Map cfs=new HashMap();
//定义一个String数组,来存储方法名
String[] methodNames;

public Session() {
    cfs.put("_id", "id");
    cfs.put("_name", "name");
    cfs.put("_age", "age");
    methodNames=new String[cfs.size()];
}

public void save(Student s) throws Exception{
    //创建sql语句
    String sql=createSql();
    //加载驱动类
    /*Class.forName("com.mysql.jdbc.Driver");
    Connection conn=DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/hibernate",
                    "root",
                    "");
    PreparedStatement pst=conn.prepareStatement(sql);



    pst.executeUpdate();
    pst.close();
    conn.close();*/

}

private String createSql() {
    String str1="";
    //定义变量,用来存储方法名数组的下标
    int index=0;
    for(String s:cfs.keySet()){
        //通过键获取值
        String value=cfs.get(s);
        //将值的首字母转换成大写
        value=Character.toUpperCase(value.charAt(0))+value.substring(1);
        //获取方法名
        methodNames[index]="get"+value;
        System.out.println(methodNames[index]);
        index++;
        str1+=s+",";
    }
    str1=str1.substring(0, str1.length()-1);
    System.out.println(str1);

    String str2="";
    for(int i=0; i<cfs.size(); i++){
        str2+="?,";
    }
    str2=str2.substring(0, str2.length()-1);
    System.out.println(str2);
    String sql="insert into "+tableName+" ("+str1+") value("+str2+")";
    System.out.println(sql);
    return sql;
}

}

  • 写回答

1条回答

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-02-25 16:50
    关注

    该回答引用ChatGPT

    在代码中,methodNames 数组是用来存储属性对应的 getter 方法名的。因为 Session 类的实例化是在程序运行时进行的,所以在构造函数中初始化 methodNames 数组可以保证它在使用时已经被正确地初始化。


    如果把 methodNames 数组的初始化放在构造函数外面,那么初始化时机就会变得不确定。可能会在对象构造之前被执行,导致 methodNames 数组没有被正确初始化,从而在使用时引发数组越界异常。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月20日

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗