Javaのインスタンス化の挙動について少し納得できない事があります。
以下はDBから全件取得し、それをインスタンスに化し、リストに挿入というコードです。
Java
1 while (rs.next()) { 2 String id = rs.getString("ID"); 3 String name = rs.getString("NAME"); 4 int age = rs.getInt("AGE"); 5 Employee employee = new Employee(id, name, age); 6 empList.add(employee); 7 }
Employee employee = new Employee(id, name, age); empList.add(employee);
この部分ですが毎回 「Employee employee」 が生成されることになりますが同じ 「employee」を何度も使用して良いのですか。
Java
1Sample sample1 = new sample(); 2Sample sample2 = sample1;
のようにするとsample1,2共に同じところを指しますよね。ですので以下のようにするべきではと思いました。
Java
1while (rs.next()) { 2 String id = rs.getString("ID"); 3 String name = rs.getString("NAME"); 4 int age = rs.getInt("AGE"); 5 empList.add(new Employee(id, name, age)); 6 }
回答5件
あなたの回答
tips
プレビュー