Java 17 String类 ArrayList集合

 

 String 运算 内存图

 

 创建字符串String的两种方式

 

 

package com.heima.StringDemo;

public class StringDemo1 {
    public static void main(String[] args) {
        //目标:String 类创建字符串对象的两种方式
        //方式一 :直接使用双引号得到字符串对象
        String name="我爱你中国";

        System.out.println(name);

        //方式二
        //1 public String();创建一个空白的字符串,不含任何内容(几乎不用)
        String s1=new String();//s1="";
        System.out.println(s1);


        //2 public String(String); 更具传入的字符串内容,来创建字符串对象(几乎不用)
        String s2=new String("我是中国人");
        System.out.println(s2);

        //3 public  String(char[] c);更具字符串数组的内容,来创建字符串对象(遍历完char[] 并将里面的字符进行拼接)
        char[] chars={'a','b','中','国'};
        String s3=new String(chars);
        System.out.println(s3);//ab中国


        //4 public String(byte[] b) ;根据直接数组的类容,来创建字符串对象(将byty内的数字 全部转换成字符)
        byte[] bytes={111,97,55,23};//bytes 取值范围 -128-127;
        String s4=new String(bytes);//
        System.out.println(s4);//oa7

    }
}
View Code

 

public class StringDemo2 {
    public static void main(String[] args) {
        //直接使用""号创建的字符串 会在字符串常量池中存储(堆内存中),相同内容只会在其中存储一份
        String s1="abc";
        String s2="abc";
        System.out.println(s1==s2);//true

        //使用new String(str); 创建的字符串 , 每次都会产生一个新对象,存储在堆内存中
        char[] chars1={1,'b','c'};
        String s3=new String(chars1);
        String s4=new String(chars1);
        System.out.println(s3==s4);//false;
    }
}
View Code

 

 

常见面试题

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

package com.heima.StringDemo;

import java.util.ArrayList;

public class StrLogin {
    public static void main(String[] args) {
        //ArrayList 集合  它支持索引
        //1创建ArrayList集合的对象
        ArrayList list=new ArrayList();

        //2 添加数据 ArrayList.add(E element);
        list.add("java");
        list.add("HTML");
        list.add("JS");
        list.add("Vue");
        System.out.println(list);


        //3 给指定索引位子插入元素add(int index,E element);
        list.add(1,"React");
        System.out.println(list);
    }
}
View Code

 

posted @ 2022-06-23 11:00  还有什么值得拥有  阅读(48)  评论(0编辑  收藏  举报