数组尾部追加数据的代码实现 java 1025

507 阅读1分钟
public class test {
    public static void main(String[] args) {

        // 定义一个空的数据
        String[] con = new String[6];

        // 给两个初始值
        con[0] = "hello";
        con[1] = "java";

        // 要插入的值
        String a = "good";

        // 遍历出所有的数组下标,用于访问其中的值
        for (int i = 0; i < con.length; i++) {
            System.out.println(i);
            // 判断下标i所对应的值是否为null
            if (con[i] == null) {
                con[i] = a;
                break;
            }
        }

        // 再次插入数据
        String b = "morning";
        for (int i = 0; i < con.length; i++) {
            System.out.println(i);
            // 判断下标i所对应的值是否为null
            if (con[i] == null) {
                con[i] = b;
                break;
            }
        }


        System.out.println("...");

        // 验证是否插入成功
        for (int j = 0; j < con.length; j++) {
            System.out.println(con[j]);
        }


    }
}