最近无意间将创建对象的操作放在外面,发现结果与预期不符。上网搜索了解如下:
在for循环外创建对象时,
创建的对象为全局变量,当进行for循环遍历时,他会不断往sb里添加内容。(我创建的是StringBuilder对象sb)
在for循环外创建对象:
创建的对象为局部变量,此时每一次for循环均会创建新的变量sb,每一次内容也就不同。
主要区别
就是在循环外创建对象会不断向那个对象添加内容
在for循环外创建对象
package com.itheima_集合到文件改进;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class ArraylistToFileDemo {
public static void main(String[] args) throws IOException {
//创建ArrayList集合
ArrayList<Student> array = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("itheima001", "林青霞", 30, "西安");
Student s2 = new Student("itheima002", "赵曼玉", 35, "武汉");
Student s3 = new Student("itheima003