2021-07-31

1.局部内部类:


局部内部类就是在局部方法中的创建的类;

局部内部类可以访问外部类的私有成员变量;

在外部类访问局部内部类的方法是创建当前内部类对象来访问;

class Outer{
        public int num = 100 ;
        private int num2 = 200 ;
    //成员方法
    public void method(){
     //局部位置:局部内部类
        class Inner{
         /局部内部类的一个成员方法
      ublic void show(){
               System.out.println(num);
               System.out.println(num2);
           }
        }

        //创建局部内部类对象
        Inner inner = new Inner() ;
        inner.show() ;
    }
}
//测试类
public class OuterDemo {
    public static void main(String[] args) {

        //访问方式:直接创建外部类类对象
        //调用的成员方法
        Outer outer = new Outer() ;
        outer.method();
    }
}

局部内部类访问成员方法的注意事项:

局部变量的生命周期是随着方法调用而存在,随着方法调用结束而消失

  •                 而当前外部类对象调用method 方法的时候,此时num进入栈内存,在局部位置创建了局部内部类对象
    
  •                 而局部内部类对象调用它的成员方法访问该变量,方法method方法结束之后,内部类对象不会立即消失,
    
  •                 它里面的成员方法在访问局部变量,局部变量必须变成常量,常驻内存,否则如果当前变量消失了,局部内部类的成员依然在访问
    
  •                 就会出现冲突! 所以 jdk7 收到必须加入final修饰,jdk8通过jvm已经做了优化了,无需手动加入final修饰
    

匿名内部类:

没有名字的内部类一般使用在局部位置

格式

new 类名 (){

重写功能

}

匿名类的本质:

继承该类或者实现该接口的子类对象;

class Outer3{

    //定义一个成员方法
    public void method(){
       // class Inner3{} 有名字内部类
        //使用匿名内部类去写
        /*
        new 类名(可以是抽象类,也可以具体类)或者是接口名(){
                   重写功能
         } ;

         */


        //情况1:接口中只有一个方法
     /*   new Inter(){ //接口名

            @Override
            public void show() {
                System.out.println("show Inter...");
            }
        }.show() ;*/

     //情况2:接口中有两个方法
      /*   new Inter(){

             @Override
             public void show() {
                 System.out.println("show Inter...");
             }

             @Override
             public void show2() {
                 System.out.println("show2 Inter...");
             }
         }.show() ;
        new Inter(){

            @Override
            public void show() {
                System.out.println("show Inter...");
            }

            @Override
            public void show2() {
                System.out.println("show2 Inter...");
            }
        }.show2() ;*/

        //优化:给匿名内部类起一个名字
        Inter i = new Inter(){

            @Override
            public void show() {

                System.out.println("show Inter...");
            }

            @Override
            public void show2() {
                System.out.println("show2 Inter...");
            }
        };
        i.show();
        i.show2();

    }
}

//测试类
public class OuterDemo3 {
    public static void main(String[] args) {
        //创建Outer3类对象
        Outer3 outer3 = new Outer3() ;
        outer3.method();

    }
}

方法的形式参数如果是接口,实际参数要传递接口子实现类:

1.创建一个子实现类;接口多肽;

2.使用匿名内部类;

interface Mary{
    void mary() ;
}

//定义一个LoveDemo类
class LoveDemo{
    public void funciton(Mary mary){//形式参数是一个接口
        mary.mary();
    }
}

//定义一个子类实现类
class You implements  Mary{

    @Override
    public void mary() {
        System.out.println("要结婚了,很开心...");
    }
}

//测试类
public class LoveTest {
    public static void main(String[] args) {
        //方式1:需要调用LoveDemo类中的function方法
        LoveDemo loveDemo  = new LoveDemo() ; //或者使用匿名对象
        //接口多态
        Mary mary = new You() ;
        loveDemo.funciton(mary);


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

        //方式2:接口的匿名内部类
        //创建LoveDemo类对象
        LoveDemo ld = new LoveDemo() ;
        ld.funciton(new Mary() {


            @Override
            public void mary() {
                System.out.println("要结婚了,很开心...");
            }
        });
    }
}

方法的形式参数如果是一个抽象类,那么实际参数可以需要接口的子类对象:

1.将子类定义出来 继承自抽象类;

2.直接使用抽象类的匿名内部类;

abstract  class Person{
    public  abstract  void work() ;
}

//PersonDemo类
class PersonDemo{
    public void method(Person p){//方法的形式参数是一个抽象类
        p.work();
    }
}

//定义一个子类继承自Person类
class Student extends  Person{

    @Override
    public void work() {
        System.out.println("good good study ,day day up!!");
    }
}

//测试类
public class PersonTest {
    public static void main(String[] args) {
        //调用PersonDemo类中的method方法?
        //创建PersonDemo类对象 /或者匿名对象
        PersonDemo pd = new PersonDemo() ;
        //抽象类多态:创建子类对象
        Person p = new Student() ; //定义一个子类Student
        pd.method(p) ;
        System.out.println("----------------------------------------");

        //使用匿名内部类去完成:
        /**
         * new 类名(抽象类)/接口名(){
         *     重写方法
         * } ;
         */

        //调用PersonDemo类中的method方法?
        PersonDemo pd2 = new PersonDemo() ;
        pd2.method(new Person(){ //实际参数也是传递抽象类的子类对象(抽象类的匿名内部类)

            @Override

            public void work() {
                System.out.println("good good Study,day day Up!!");
            }
        });
    }
}

面试题:

 * 考点:
 *  外部类直接访问非静态的成员内部类的格式
 *  外部类的成员变量的方法方式,(在成员内部类的成员方法中)
 *  成员变量,局部变量名称都一样(就近原则)
 *  外部类和内部类没有继承关系
 *
 */
class Outer{
    int num = 10 ;

    //成员内部类
    class Inner{
        int num = 20 ;
        public void show(){
            int num = 30;
            //补全代码
            System.out.println(num);
            System.out.println(this.num);//this限定 :this.变量名:当前类的成员变量
           // System.out.println(new Outer().num) ; //方式1:new Outer().num

            System.out.println(Outer.this.num) ; //方式2:外部类的this限定
        }
    }
}
public class OuterTest {
    public static void main(String[] args) {
            Outer.Inner oi = new Outer().new Inner() ;
            oi.show();
    }
}

* 笔试题
 * 补全代码--->在控制台输出"HelloWorld"

 *给定一个接口
 * interface Inter{
 *     void show()  ;
 * }
 * class Outer{
 *
 *
 *     //补全代码
 * }
 *
 *
 * class Test{
 *     public static void main(String[] args){
 *         Outer.method().show() ;
 *     }
 * }
 *
 *
 */
interface Inter{
    void show() ;
}
class Outer2{
    public static Inter method(){
        //返回结果?
        //返回值是一个接口类型,需要返回的是接口的子实现类对象
        //方式1:定义子实现类(不让我们创建子类)
        //方式2:可以使用接口匿名内部类(考点)
        return new Inter(){
            @Override
            public void show() {
                System.out.println("HelloWorld...");
            }
        } ;
    }
}
public class Test {
    public static void main(String[] args) {
       /* Inter inter = Outer2.method(); //Inter inter = new 子实现类() ;匿名内部类的方式完成的
                inter.show() ;*/
       Outer2.method().show();
        /**
         * 类名.method()----->说明当前这个是一个静态方法
         * Outer2.method().show()---->前面部分Outer2.method()--->是由返回值类型的方法, 可以调用接口中的show方法
         * show方法是接口的方法,所以返回的接口类型
         *
         */

    }
}

方法的返回值是接口类型,需要返回的当前接口的子实现类对象

interface Love{
    void love() ;
}
class LoveDemo{
    public Love function(){
        //return ?

        //通过接口多态
        //Love love = new Student() ;
        //return love ;
        //匿名对象
       // return new Student() ;


        //使用接口的匿名内部类
        /**
         * new 类名/接口名(){
         *
         *     重写方法
         * } ;
         */
        return  new Love(){

            @Override
            public void love() {
                System.out.println("爱Java,爱学习...");
            }
        } ;
    }
}

//定义接口的子实现类
class Student implements  Love{

    @Override
    public void love() {
        System.out.println("爱Java,爱学习...");
    }
}

//测试类
public class LoveTest {
    public static void main(String[] args) {
        //要访问LoveDemo类中的function方法
        LoveDemo ld = new LoveDemo() ;
        Love love = ld.function();//Love love  =  new Student() ;
        love.love();

        System.out.println("------------------");
        //方式2:接口匿名内部类的方式
        LoveDemo ld2 = new LoveDemo() ;
        Love l = ld2.function();
        l.love();

    }
}

方法的返回值是一个抽象类?需要返回的是当前抽象类的子类对象:

abstract  class Person{

    public abstract  void work() ;

}

class PersonDemo{
    public Person method(){
         //return ?
        //抽象类多态
       // Person person = new Programmer() ;
       // return  person ;
       // return new Programmer() ;


        //直接抽象类的匿名内部类
        return new Person(){//相当于Person类的子类对象(匿名内部类的本质)


            @Override
            public void work() {
                System.out.println("程序员日日夜夜敲代码");
            }
        } ;
    }
}
//定义一个子类
class Programmer extends  Person{

    @Override
    public void work() {
        System.out.println("程序员日日夜夜敲代码...");
    }
}

//测试类
public class PersonTest {
    public static void main(String[] args) {
        //调用PersonDemo类中的method 方法
        PersonDemo pd = new PersonDemo() ;
        Person person = pd.method(); //Person pserson = new Programmer() ;
        person.work();


        System.out.println("--------------------------");
        //方式2:匿名内部类
        PersonDemo pd2 = new PersonDemo() ;
        Person p = pd2.method();
        p.work();
    }
}

Object:

Object是类结构层次的根类(超类–>父类),

所有的类都默认继承Object子类;

Object功能类的getClass()方法

public final Class getClass():表示正在运行的类 (就是字节码文件对象)

public String getName():获取当前类的全限定名称(包名.类名)
获取一个类的字节码文件对象有几种方式? 三种

第一种:通过Object类的getClass()—>Class :正在运行的java类: class 包名.类名
第二种:任意Java类型的class属性----获取当前类的字节码文件对象Class

第三种方式:Class里面forName(“类的全限定名称(包名.类名)”) ; (使用最多)

面试题:

 *     面试题:
 *
 *          获取一个类的字节码文件对象有几种方式? 三种
 *                   第一种:通过Object类的getClass()--->Class       :正在运行的java类: class  包名.类名
 *
 *                   第二种:任意Java类型的class属性----获取当前类的字节码文件对象Class
 *                   第三种方式:Class里面forName("类的全限定名称(包名.类名)") ; (使用最多)
 */
public class ObjectDemo {

    public static void main(String[] args) throws ClassNotFoundException {
        //创建一个学生类对象
        Student s  = new Student() ;
        Class c1 = s.getClass();
        System.out.println(c1);//class com.qf.generator_class_05.Student    class 包.类名
        Class c2 = s.getClass();
        System.out.println(c2);//class com.qf.generator_class_05.Student    class 包名.类名
        System.out.println(c1 == c2);
        //==在基本数据类型里面:比较的是数据值相同,在引用类型:比较的是两个对象的地址值是否相同
        //Student.class---->就加载一次
        System.out.println("---------------------------------");
        Student s2 = new Student() ;
        System.out.println(s == s2);//false :两个对象


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

        //获取c1/c2 所代表的类 的全限定名称
        // Class ---->class com.qf.generator_class_05.Student
        String name1 = c1.getName();
        String name2 = c2.getName();
        System.out.println(name1);
        System.out.println(name2);

        System.out.println("--------------------------------");
        //Class类中public static Class forName(String classname): 后期反射中使用
        Class c3 = Class.forName("com.qf.generator_class_05.Student");
        System.out.println(c1==c3);
        System.out.println(c2==c3);
        System.out.println("--------------------------------");
        Class c4 =  Student.class ; //任意Java类型的class属性----获取当前类的字节码文件对象Class
        System.out.println(c4);
        System.out.println(c1==c4);
        System.out.println(c2==c4);
        System.out.println(c3==c4);


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

        //创建两个对象
        // public int hashCode()
        Student s3 = new Student() ;
        Student s4 = new Student() ;
        System.out.println(s3.hashCode());
        System.out.println(s4.hashCode());
        System.out.println("helloworld".hashCode());
        System.out.println("javaee".hashCode());
        System.out.println("helloWorld".hashCode());
        System.out.println("helloworld".hashCode());


    }
}

Object的public String toString():

Object的public String toString(),返回对象的字符串表示形式。结果应该是一个简明扼要的表达,容易让人阅读。建议所有子类覆盖此方法。
描述一个对象:是由很多属性(成员变量组成),应该看到的具体的属性描述,要么手动方式(不推荐),也可以直接快捷键----重写toString即可, 大部分的常用类或者后面的集合都会重写Object类的toString()

举例

public class ObjectDemo {
    public static void main(String[] args) {

        //通过有参构造方法创建一个学生对象
        Student s = new Student("高圆圆",42) ;
        //直接输出对象名称 --->会默认调用它的父类:Object的toString方法
        System.out.println(s);//com.qf.object_06.Student@1540e19d
        System.out.println("-----------------------------------");
        /**
         * Object类的toString方法的原码
         *  public String toString() {
         *         return getClass().getName() + "@" + Integer.toHexString(hashCode());
         *     }
         *
         *     Integer类:int类型的包装类类型
         *          public static String toHexString(int i) :将整数转换成16进制数据--结果以String类型展示
         */
        /*System.out.println(s.getClass().getName()+"@"+Integer.toHexString(s.hashCode()));
        System.out.println(s.toString());*/
        System.out.println(s.toString());

        /*String str = new String("hello") ;
        System.out.println(str);*/


    }
}

Object类的equals方法:

public boolean equals(Object obj),判断当前obj对象是否和当前对象想等;

面试题:

equals和==的区别?
==: 连接的基本数据类型:比较的是数据值否相同

: 连接的是引用类型,比较的是地址值是否相同equals方法:如果使用Object默认的:底层用,默认比较的还是两个对象的地址值是否相同,

Student s1 = new Student(“文章”,35) ;

Student s2 = new Student(“文章”,35) ;
s1和s2虽然地址值不同,他们的成员的内容相同,认为他是同一个人,但是如何让s1.equals(s2)为true:针对equals来说

比较的是成员信息内容是否相同;

重写Object的equals方法同时还需要重写hashCode

内容相同,还需要比较哈希码值相同
alt+ins—>hashcode+equals方法

重写之后,就比较的是成员信息的内容是否相同!

public class ObjectDemo {
    public static void main(String[] args) {
            //==
        int a = 10 ;
        int b = 15 ;
        System.out.println(a==b);//==链接的基本数据类型:比较的是数据值否相同
        System.out.println("--------------------------------------------");

        Student s1 = new Student("文章",35) ;
        System.out.println(s1);
        Student s2 = new Student("文章",35) ;
        System.out.println(s2);
        System.out.println(s1 == s2);

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

        //public boolean equals(Object obj)//Object obj = new Student() ;多态
        System.out.println(s1.equals(s2));
        //没有重写之前:执行的是Object类的equals()
        //重写之后,就比较的是对象的成员信息是否一致!

        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println("文章".hashCode());

        /***
         *Object类中的equals的源码
         *  public boolean equals(Object obj) {   //s1 ---this    obj---->s2
         *         return (this == obj);  return s1 == s2 ;   ==:引用类型:比较的是地址值是否相同
         *     }
         */


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


//        String类型(大部分常用类都会重写equals)重写Object的equals方法,所以比较内容是否相同
        String str1 = "hello" ;
        String str2 = "hello" ;
        System.out.println(str1.equals(str2));
        String str3 = "world" ;
        String str4  = new String("world") ;
        System.out.println(str3.equals(str4));


    }
}

Object克隆方法:

protected Object clone() throws CloneNotSupportedException:创建对象并返回该对象的副本

这个方法会抛出一个异常,throws:表示的是可能出现异常,针对调用者必须进行处理
要使用clone方法,当前某个对象所在的类必须实现"标记接口"Cloneable(没有字段(成员变量),也没有成员方法)

实现这个接口,那么就可以使用Object的clone()方法

public class ObjectDemo {
    public static void main(String[] args) throws CloneNotSupportedException{
        //创建学生对象
        Student s1 = new Student("高圆圆",42) ;
        System.out.println(s1);
        System.out.println(s1.getName()+"---"+s1.getAge());

        System.out.println("-----------------------------------");
        //调用克隆方法clone()
        Object obj = s1.clone(); //已经克隆了(浅克隆:将s1地址值赋值给Objet)
        //向下转型
        Student s2 = (Student) obj;
        System.out.println(s2);
        System.out.println(s2.getName()+"---"+s2.getAge());

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

        //传统方式
        Student s3 = s1 ;
        System.out.println(s3.getName()+"---"+s3.getAge());


    }
}

Scanner类文本扫描器:

构造方法:

public Scanner(InputStream source) :创建一个文本扫描器

形式参数是一个抽象类—>

它通过System类里面的public static final InputStream in
System类中

public final static InputStream in = null;
本地方法(非Java语言实现)—> private static native void setIn0(InputStream in);

底层方法一定会创建系统资源---->读取用户输入的 字符(整数,字符串…)
Scanner类提供判断功能:防止出现输入的类型和结果类型不匹配!

public boolean hasNextXXX():判断下一个录入的是否为指定的XXX类型

XXX nextXXX() 获取功能

public class ScannerDemo {
    public static void main(String[] args) {

        //创建键盘录入对象
        InputStream inputStream = System.in ;  //标准输入流  IO(Input 读 ,Output 写)  :Java高级特性:IO

        Scanner sc = new Scanner(inputStream) ;// public Scanner(InputStream source) :创建一个文本扫描器

        System.out.println("请您输入一个数据:");

        if(sc.hasNextInt()){
            int num = sc.nextInt() ;
            System.out.println("您录入的数据是:"+num);
        }else if(sc.hasNextLine()){
            //录入的字符串
            String line = sc.nextLine() ;
            System.out.println("您录入的数据是:"+line);
        }else{
            System.out.println("您录入的数据和结果类型不匹配...");
        }
        //录入数据
       // int num = sc.nextInt();  //java.util.InputMismatchException
       // System.out.println("您要录入的数据是:"+num);
    }
}

String常用功能:

字符串是一个常量,一旦被赋值了,其值(地址值)不能被更改

推荐的使用方式:

String 变量名 = “xxxx” ;//xxxx代表 的当前String的实例
String类常用的功能:

获取功能:

int length():获取字符串长度
面试题:

@ 在数组中有没有length方法,在String类中有没有length方法,在集合中有没有length方法
数组中没有length方法,length属性

int[] arr = new int[3] ;

arr.length;
String类中有length()

集合中没有length(),----->size()获取元素数

构造方法:

public String():空参构造:空字符序列

public String(byte[] bytes):将一个字节数组构造成一个字符串,使用平台默认的字符集(utf-8:一个中文对应三个字节) 解码

编码和解码—保证字符集统一

编码:将一个能看懂的字符串---->字节 “今天老地方见” utf-8
解码:将看不懂的字节---->字符串 “今天老地方见” gbk

public String(byte[] bytes,字符集):使用指定的字符集,将字节数组构造成一个字符串

public String(byte[] bytes,int offset,int length):将指定的部分字节数组转换成字符串

参数1:字节数组对象,参数2:指定的角标值 参数3:指定长度
public String(char[] value):将字符数组构造成一字符串

public String(char[] value,int offset,int count):将部分字符数组转换成字符串

public String(String original):构造一个字符串,参数为字符串常量

public class StringDemo {
    public static void main(String[] args) {
            //测试
        String s = new String() ;
        System.out.println("s:"+s); //String类重写了Object的toString(),
        System.out.println(s.length());
        System.out.println("-------------------------------------------");

        byte[] bytes = {97,98,99,100,101} ;
        // public String(byte[] bytes)
        String s2 = new String(bytes) ;
        System.out.println(s2);
        System.out.println(s2.length());

        System.out.println("-------------------------------------------");
        //public String(byte[] bytes,int offset,int length):
        String s3 = new String(bytes,2,2) ;
        System.out.println(s3);
        System.out.println(s3.length());
        System.out.println("-------------------------------------------");

        //public String(char[] value)
        char[] chs = {'我','爱','高','圆','圆'} ;
        String s4 = new String(chs) ;
        System.out.println(s4);
        System.out.println(s4.length());
        System.out.println("-------------------------------------------");

      //  public String(char[] value,int offset,int count)
        String s5 = new String(chs,1,4) ;
        System.out.println(s5);
        System.out.println(s5.length());

        System.out.println("---------------------------------------------");
        // public String(String original)
        String s6 = new String("hello") ; //创建字符串对象,常量值:hello
        System.out.println(s6);
        String s7 = "hello" ; //推荐的方式
        System.out.println(s7);


    }


}

面试题:

String s1 = “hello” ;

String s2 = new String(“hello”) ;

在内存中分别创建了几个对象?
第一个创建了一个对象,直接在常量池创建,开辟常量池空间

第二个:创建了两个对象,一个堆内存中开辟空间,一个指向常量池(不推荐)

public class StringDemo2 {
    public static void main(String[] args) {

        String s1 = "hello" ;
        String s2 = new String("hello") ;
        System.out.println(s1 == s2);
       System.out.println(s1.equals(s2));  //只管内容相同
    }
}
/**
 * String类型重写了Object的equals方法
 * Object 的equals
 *
 *  public boolean equals(Object obj) {
 *         return (this == obj);   //默认比较的地址值
 *     }
 *
 *
 * class String{
 *
 *  private final char value[];  属性 value 字符数组
 * public boolean equals(Object anObject) {  Object anObject = new String() ;
 *         if (this == anObject) {  //判断当前字符串对象和传递进来S2对比
 *             return true;         //判断地址值相同
 *         }
 *         if (anObject instanceof String) {    //判断传进来的s2是否为String类型的实例
 *             String anotherString = (String)anObject; // 向下转型  String类型
 *             int n = value.length;            //获取了字符数组长度   this.value.length---->  int n = 5
 *             if (n == anotherString.value.length) {  //  if(s1的长度 5 == s2.value.length   5)
 *                 char v1[] = value;                  //char v1[] = this.value;  将s1---->v1字符数组
 *                                                      char v1[] = {'h','e','l','l','o'}
 *                 char v2[] = anotherString.value;     //char v2[] =s2.value; 将s2----->v2字符数组
 *                                                      char v2[]  = {'h','e','l','l','o'}
 *                 int i = 0;               //统计变量
 *                 while (n-- != 0) {        // i=0
 *                     if (v1[i] != v2[i])      // v1[0] != v2[0]  ---->'h'     v1[1] != v2[1]
 *                         return false;
 *                     i++;                 /i=1
 *                 }
 *                 return true;         //true
 *             }
 *         }
 *         return false;
 *     }
 *
 *   }
 */

==和equals的区别:

== 和equals

==:连接引用类型比较的是地址值

equals:默认比较地址值,但是String类重写equals方法,所以内容是否相同
看程序,写结果

直接赋值的形式

字符串变量相加,常量池中先开空间,在拼接

字符串常量相加,先相加,然后看结果是否在常量池中存在;

如果存在,直接返回当前地址值,如果不存在,在常量池开辟空间!

public class StringTest {
    public static void main(String[] args) {

        String s1  = "hello" ;
        String s2 =  "world" ;
        String s3 = "helloworld" ;

        System.out.println(s3 == (s1+s2)); //s1+s2:先开空间,在拼接  false
        System.out.println(s3.equals(s1+s2)); //true
        System.out.println("----------------------");
        System.out.println(s3 == "hello"+"world"); //先拼接,然后再常量池中找,存在,直接返回地址
        System.out.println(s3 .equals("hello"+"world"));
    }
}

@ String类的常用的转换功能:

byte[] getBytes() :将字符串转换成字节数组 (编码)

如果方法为空参,使用平台默认的编码集进行编码(utf-8:一个中文对应三个字节)

byte[] getBytes(String charset):使用指定的字符集进行编码

解码的过程:将看不懂的字节数----->String

String(byte[] bytes):使用默认字符集进行解码

String(byte[] bytes,指定字符集)
编码和解码必须要保证字符集统一字符集:

gbk :一个中文两个字节(中国中文编码表)

gb2312:gbk升级版(含义有一个中文字符:中国的中文编码表)

iso-8859-1:拉丁文码表

utf-8:任何的浏览器—>都支持 utf-8格式 (后期统一个)

unicode:国际编码表

S:日本国际 电脑系统 一个字符集
Arrays

静态功能:

public static String toString(int/byte/float/double…[] a):将任意类型的数组---->String
public char[] toCharArray():将字符串转换成字符数组

public String toString():返回自己本身—“当前字符串的内容”

public String toUpperCase():将字符串转换成大写

public String toLowerCase():将字符串转换成小写

public class StringDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {

        //定义一个字符串
        String str = "中国" ;
        byte[] bytes = str.getBytes();//默认utf-8
       // byte[] bytes = str.getBytes("gbk");//指定字符集
       // public static String toString(byte[] a)
        System.out.println(Arrays.toString(bytes));//[-28, -72, -83, -27, -101, -67]
                                                    //[-42, -48, -71, -6]


        System.out.println("------------------------------");
        //解码
       // String strResult = new String(bytes,"gbk") ;//gbk:一个中文对应两个字节 //使用平台默认解码集进行解码:   utf-8
      String strResult = new String(bytes) ;// //使用平台默认解码集进行解码:   utf-8

        System.out.println(strResult);

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

        //定义一个字符串
        String s2 = "helloworldJavaEE" ;
        // public char[] toCharArray()
        char[] chs = s2.toCharArray();
        //遍历字符数组
        for(int x = 0 ; x < chs.length;  x ++){
            System.out.println(chs[x]);
        }
        System.out.println("-----------------------");
        System.out.println(s2.toString());

        System.out.println("-----------------------");
        //转换大小写
        System.out.println(s2.toUpperCase());
        System.out.println(s2.toLowerCase());

    }
}

String类型的判断功能:

public boolean equals(Object anObject):比较两个字符的内容是否相同 (区分大小写)

public boolean equalsIgnoreCase(String anotherString):比较两个字符串是否相同(不区分大小写)

public boolean startsWith(String prefix):判断字符串是否以指定的内容开头

public boolean endsWith(String suffix):判断字符串是否以指定的内容结尾

需求:在某个时间点(今天下午18:00 将某个目录下的所有的以.java文件结尾删除)

Java中定时器类:Timer---->定时任务TimerTask(抽象类)

表示文件或者文件夹的抽象路径形式:File类

递归删除 (定义方法删除)
boolean isEmpty() 判断字符串是否为空 :若为空,则返回true;否则返回false

String s = “” ;// 空字符串 ,存在String对象 “”

String s = null ; 空值 (空对象) null:引用类型的默认值

public class StringDemo2 {
    public static void main(String[] args) {

        String s1 = "helloJavaEE" ;
        String s2 = "hellojavaee" ;
        //  public boolean equals(Object anObject):比较两个字符的内容是否相同 (区分大小写)
        System.out.println("equals:"+s1.equals(s2));
        //   public boolean equalsIgnoreCase(String anotherString)
        System.out.println("equalsIgnoreCase():"+s1.equalsIgnoreCase(s2));
        /**
         *     public boolean startsWith(String prefix):判断字符串是否以指定的内容开头
         *      public boolean endsWith(String suffix):判断字符串是否以指定的内容结尾
         *      boolean isEmpty()  判断字符串是否为空 :若为空,则返回true;否则返回false
         */
        System.out.println("startsWith():"+s1.startsWith("hel"));
        System.out.println("startsWith():"+s1.startsWith("ak47"));
        System.out.println("endsWith():"+s1.endsWith("EE"));
        s1 = "" ; //length()---->长度0 (空字符序列)
        System.out.println(s1.isEmpty());
    }
}

@String类的获取功能:

int length():获取字符串长度

public char charAt(int index);获取指定索引处的字符

public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串

public int indexOf(int ch):返回指定字符第一次出现的索引值

public int lastIndexOf(int ch):返回值指定字符最后一次出现的索引值

public String[] split(String regex):拆分功能:通过指定的格式将字符串—拆分字符串数组

public String substring(int beginIndex) :从指定位置开始默认截取到末尾

角标从0开始

public String substring(int beginIndex,int endIndex)

从指定位置开始,截取到位置结束(包前不包右)

只能取到endIndex-1处
public static String valueOf(boolean/int/long/float/double/char…Object b)万能方法,将任意类型转换String类型

public class StringDemo {
    public static void main(String[] args) {

        String str = "helloworldJavaEE" ;
        // public char charAt(int index);获取指定索引处的字符
        System.out.println("charAt():"+str.charAt(4));
        System.out.println("---------------------------------");
        //public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串
        //字符串最传统的拼接:直接  定义一个String s = "" ;  s+任何数据="xxx" ;
        //提供了一个功能
        System.out.println("concat:"+str.concat("R").concat("Go"));
        System.out.println("-----------------------------------");

        //   public int indexOf(int ch):返回指定字符第一次出现的索引值
        // public int lastIndexOf(int ch):返回值指定字符最后一次出现的索引值
        System.out.println("indexOf():"+str.indexOf("o"));
        System.out.println("lastIndexOf():"+str.lastIndexOf("o"));
        System.out.println("-----------------------------------");
        //public String[] split(String regex):
        String str2 = "JavaEE-Python-Go-R-C-C#-PHP" ;
        //使用"-"进行拆分
        String[] strArray = str2.split("-");
        for(int x = 0 ; x < strArray.length ; x ++){
            System.out.print(strArray[x]+"\t");
        }
        System.out.println();
        System.out.println("-----------------------------------");
        /**
         *  public String substring(int beginIndex) :从指定位置开始默认截取到末尾
         *                                    角标从0开始
         *  public String substring(int beginIndex,int endIndex)
         */
        // String str = "helloworldJavaEE" ;
        System.out.println("subString():"+str.substring(5));
        System.out.println("subString():"+str.substring(5,9));//worl
        System.out.println("-----------------------------------");
        //public static String valueOf(基本类型以及Object)
        System.out.println("valueOf:"+String.valueOf(100)); //100--->"100"

    }
}

字符串的其他功能:

public String replace(char target,char replacement):替换功能

将指定的内容使用target字符进行替换
public String replaceAll(String regex, String replacement) :

将指定的和参数1正则表达式匹配的字符串 使用replacement进行替换

参数1:

[0-9] —>如果字符是数字字符

参数2: "*"替换掉
public String trim():去除字符串两端的空格

重点

public int compareTo(String anotherString):按照字典顺序比较,返回值是int

public class StringDemo2 {
    public static void main(String[] args) {

        String s = "helloworld" ;
        System.out.println("replace():"+s.replace('l','k'));
        System.out.println("-------------------------------------");
        //public String trim():去除字符串两端的空格
        //
        /**
         * 网页中;填写日期的时候
         * 应用场景:
         *              在IO流中:可能数据传输过程中: "      hello     " ,可以通过trim去除空格  (数据网络中传输,获取字符串数据之后,先去除空格,然后再操作!)
         *            String 文本  "2021-7-27"------>日期对象  Date
         *                  解析过程: 如果日期文本中有空格字符串---->解析就会发生异常,去除两端空格
         */
        String s2 = "hello";
        System.out.println("s2:"+s2+"----");
        String s3 = "      hello  " ;
        System.out.println("s3:"+s3);
        System.out.println("s3:"+s3.trim()+"----");

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

//        public int compareTo(String anotherString):按照字典顺序比较,返回值是int

        String str1 = "abc" ;//字典顺序:就是我们26个字母,a,b,c,d,e,f,g,h
        String str2 = "hello" ;
        System.out.println(str1.compareTo(str2));
        String str3 = "hel" ;
        System.out.println(str2.compareTo(str3));

        /**
         * 面试题
         *      String s1 = "hello" ;
         *      String s2 = "hel" ;
         *
         *      使用s1调用compareTo(s2):按照字典顺序比较:结果是多少?
         *      是怎么运行的?   长度相减
         *
         *      2
         *
         */
    }
}

StringBuffer:

StringBuffer:字符串缓冲区 ---->类似于String,但是不一样 (可变的字符序列)

线程安全------>线程----(多线程中说)

线程依赖于进程存在!进程,能够被系统资源调用的独立单位

一个进程可以有多个线程,每一个线程----->“执行单元”(任务)
线程安全---->同步的----->执行效率低

举例:

银行类的网站/医疗网站

ATM机取钱---->插卡—>输入密码---->查询余额---->取钱

StringBuilder:和StringBuffer具有相互兼容的API,它是线程不安全的类---->不同步----->执行效率高

举例:

论坛网站

博客…

单线程程序中:jvm在进行编译的时候 使用StringBuilder去替换StringBuffer

StringBuffer的构造方法:

public StringBuffer() :空参构造,创建一个空字符序列的字符串缓冲去 (推荐)

public StringBuffer(int capacity):构造一个字符串缓冲区对象,指定容量大小

public StringBuffer(String str):指定字符序列,长度加上初始容量16(总容量)
获取功能:

public int length():获取字符数(长度)

public int capacity():获取字符串缓冲区容量

public class StringBufferDemo {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer() ;
        System.out.println("sb:"+sb); //空字符序列;重写Object的toString()
        System.out.println(sb.length());
        System.out.println(sb.capacity());
        System.out.println("------------------------------");
        StringBuffer sb2 = new StringBuffer(20) ;
        /**
         *  内部实现---->调用父类的构造函数: 相当于内部创建了一个字符数组对象
         *    AbstractStringBuilder(int capacity) {
         *         value = new char[capacity];
         *     }
         */
        System.out.println("sb2:"+sb2);
        System.out.println(sb2.length());
        System.out.println(sb2.capacity());

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



        StringBuffer sb3  = new StringBuffer("hello") ; //'h','e','l','l','o'
        System.out.println("sb3:"+sb3);
        System.out.println(sb3.length());
        System.out.println(sb3.capacity());


        //StringBuffer sb4 = "world" ;
       // String str = "world" ;
      //  StringBuffer sb4 = str ;

        //String---->StringBuffer  :有的时候使用的String类型的功能,但是结果需要一个StringBuffer类型
        //StringBuffer--->String :可能使用过程中用的StringBuffer的功能,最终需要String类型

    }
}

StringBuffer: 线程安全的类 (执行效率低) :字符串缓冲区:里面存储的字符序列

添加功能:

StringBuffer append(任何类型) :将内容追加到字符串缓冲区中 (在字符串缓冲区的最后一个字符序列的末尾追加)

返回值是字符串缓冲区本身…
public StringBuffer insert(int offset,String str):插入:在指定位置处插入指定的内容

public class StringBufferDemo {
    public static void main(String[] args) {
        //创建一个字符串缓冲区对象
        StringBuffer sb = new StringBuffer() ;
        System.out.println("sb:"+sb);
        //StringBuffer  append(任何类型)
       sb.append("hello").append("world").append(100).append('a').append(12.34).append(new Object()) ;
        System.out.println("sb:"+sb);


        System.out.println("----------------------------------");
        //public StringBuffer insert(int offset,String str)
        sb.insert(5,"高圆圆") ;
        System.out.println("sb:"+sb);


    }
}

StringBuffer的删除功能:

public StringBuffer deleteCharAt(int index):删除指定索引处的缓冲区的字符序列,返回字符串缓冲区本身

public StringBuffer delete(int start,int end):删除从指定位置到指定位置结束的字符序列(包含end-1处的字符),返回字符串缓冲区本身,[start,end-1]

public class StringBufferDemo2 {
    public static void main(String[] args) {

        //创建一个StringBuffer对象 (默认初始容量16)
        StringBuffer buffer = new StringBuffer() ;
        buffer.append("hello").append("world").append("Javaee") ;
        System.out.println(buffer);

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

        //public StringBuffer deleteCharAt(int index)
        //删除e这个字符
       // System.out.println("deletCharAt():"+buffer.deleteCharAt(1));
        //删除第一个l字符
       // System.out.println("deletCharAt():"+buffer.deleteCharAt(1));

        //public StringBuffer delete(int start,int end):
        //删除world这个子字符串
        System.out.println("delete():"+buffer.delete(5,10));//5-9

    }
}

String 与StringBuffer的转化:

本身A类型,由于需要使用B类型的功能,所以 A类型---->B类型
A类型,需要使用B类型的功能,A—>B类型,使用完功能之后,又可能结果又需要A类型,

B类型---->A类型

String---->StringBuffer

StringBuffer---->String

public class StringBufferDemo3 {
    public static void main(String[] args) {

        //String---->StringBuffer
        String s = "hello" ;
        //错误的写法
       // StringBuffer sb = s ;//两个类型不一致

        //方式1:StringBuffer有参构造方法
        StringBuffer sb = new StringBuffer(s) ;
        System.out.println(sb);

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

        //方式2:StringBuffer的无参构造方法 结合append(String str)
        StringBuffer sb2 = new StringBuffer() ;
        sb2.append(s) ;//追加功能
        System.out.println(sb2);


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

        //StringBuffer---->String
        //创建字符串缓冲区对象
        StringBuffer buffer = new StringBuffer("helloJavaee") ;
        //方式1:String类型的构造方法
        //public String(StringBuffer buffer)
        String  str = new String(buffer) ;
        System.out.println(str);
        System.out.println("-------------------------------------------");

        //方式2:StringBuffer的public String toString()方法
        String str2 = buffer.toString();
        System.out.println(str2);


    }
}

StringBuffer的特有功能反转:

public StringBuffer reverse(),反转之后,返回的是字符串缓冲区本身

键盘录入一个字符串,将字符串进行反转—>使用功能改进

public class StringBufferDemo4 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in) ;

        //提示并录入
        System.out.println("请您输入一个字符串:");
        String line = sc.nextLine() ;

        //需要用StringBuffer的特有功能 reverse
        //line---->StringBuffer类型
        StringBuffer sb = new StringBuffer(line) ;
        String result = sb.reverse().toString();
        System.out.println(result);

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

        //调用功能
        String result2 = reverse(line);
        System.out.println(result2);

    }

    /**
     * reverse反转功能
     * @param s   将指定的字符串反转
     * @return  返回结果字符串
     */
    public static String reverse(String s){

        //分步走
        //方式1:s---->StringBuffer类型---->有参构造
        //StringBuffer buffer = new StringBuffer(s) ;
        //return buffer.reverse().toString() ;

        //方式2:append()+空参构造方法
        /*StringBuffer buffer = new StringBuffer() ;
        String result = buffer.append(s).reverse().toString();
        return result ;*/


        //匿名对象
        return new StringBuffer().append(s).reverse().toString() ;

    }


}

StringBuffer的截取功能

public String substring(int start):从指定位置开始,默认截取到末尾,返回值是新的字符串

public String substring(int start,int end):从指定位置开始到指定end-1结束进行截取,返回的新的字符串
StringBuffer的替换功能

public StringBuffer replace(int start, 起始索引

int end, 结束索引(end-1)

String str) 替换的内容

public class StringBufferDemo5 {
    public static void main(String[] args) {

        StringBuffer sb = new StringBuffer() ;
        sb.append("hello").append("world").append("javaee").append("anroid") ;
        System.out.println("sb:"+sb);
       // System.out.println(sb.substring(5));//subString(xx)---->截取的新的字符串
        //System.out.println("sb:"+sb);

       // System.out.println(sb.substring(5,10));//end-1位置

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

        //public StringBuffer replace(int start,       起始索引
        //                          int end,         结束索引(end-1)
        //                              String str)      替换的内容
        System.out.println(sb.replace(5,10,"高圆圆"));
    }
}

面试题 StringBuffer和数组的区别?

数组:只能存储同一种数据类型容器

数组可以存储基本类型,也可以存储引用类型
数组的最大特点:长度固定

静态初始化int[] arr = {元素1,元素2,元素3…} ;/动态初始化 int[] arr = new int[长度];

String[] strArray = {“xx”,“xx”,“xx”} ;
StringBuffer:支持可变的字符序列

里面存储可以存储任意类型的元素

append(int/char/double/float/Obejct/String)

isnert(int offert,int/char/double/float/Obejct/String)
一般情况:开发中 将StringBuffer----->String
面试题:

StringBuffer,StringBuilder和String的区别?

String:字符串是一个常量,一旦被赋值,其值不能更改/作为形式参数属于特殊的引用类型,形式参数的改变不会实际参数

StringBuffer:可变的字符序列,线程安全的类----同步的----->执行效率低(线程角度)

StringBuilder:可变的字符序列.和StringBuffer具有相互兼容的api,单线程程序中(只考虑执行效率,不考虑安全问题),

会使用StringBuilder替代StringBuffer
作为方法的形式参数,形参的改变会直接实际参数应用场景:

Arrays.toString()—>源码 ---->StringBuilder “[]”

网络聊天室

集合+多线程+io流

私聊

公聊

在线列表

JavaSE

好友的在线列表

高圆圆—>查询当前在线列表

可以StringBuilder/StringBuffer进行追加…

1,张三

2,李四

3,王五

public class StringBufferTest {
    public static void main(String[] args) {
        //int[] arr = {11,22,33,44,55} ;//int[] arr = new int[]{11,22,33,44,55}
        //System.out.println(Arrays.toString(arr));

        String s = "hello" ;
        System.out.println("s:"+s);
        change(s) ;
        System.out.println("s:"+s);
        System.out.println("-------------------------");
        StringBuffer sb = new StringBuffer("android") ;
        System.out.println("sb:"+sb);
        change(sb) ;
        System.out.println("sb:"+sb);//androidjavaee
    }
    public static void change(StringBuffer sb){//StringBuffer作为形参
        sb.append("javaee") ;//缓存区中追加了javaee
        System.out.println("sb:"+sb);
    }
    public static void change(String s) {//String作为形参:和基本数据类型一致(String是一个常量)
        s = s +"worldjavaee" ;
        System.out.println("s:"+s);
    }
}

Integer:

Integer:int类型的包装类类型(引用类型),包含了int类型的原始数据值

基本类型四类八种都会 对应的各自的引用类型
int----->String

需要基本类型和String类型之间转换:需要中间桥梁(基本类型对应的包装类类型)
整数类型 引用类型(默认值都是null)

byte Byte

short Short

int Integer

long Long

浮点类型

float Float

double Double
字符类型

char Character

布尔类型

boolean Boolean
需求:

进制的转换----就可以使用Integer静态功能 十进制---->二进制 “以字符串形式体现”
十进制---->八进制

十六进制

通过Integer得到int类型的取值范围
public static String toBinaryString(int i):将整数---->二进制 的字符串

public static String toOctalString(int i):将整数---->八进制的字符串

public static String toHexString(int i):将整数---->十六进制数据
public static final int MAX_VALUE:int的最大值

public static final int MIN_VALUE:int的最小值

public class IntegerDemo {
    public static void main(String[] args) {
        System.out.println(Integer.toBinaryString(100));
        System.out.println(Integer.toOctalString(100));
        System.out.println(Integer.toHexString(100));

        System.out.println("----------------------");
        System.out.println(Integer.MIN_VALUE);//-2的31次方
        System.out.println(Integer.MAX_VALUE);//2的31次方-1
    }
}

IntInteger(int value):可以将int类型保证为Integer类型

Integer(String s) throws NumberForamtException: 抛出一个数字格式化异常

注意事项:

当前字符串如果不是能够解析的整数的,就会出现数字格式化异常,s必须为 数字字符串

public class IntegerDemo2 {
public static void main(String[] args) {

public class IntegerDemo2 {
    public static void main(String[] args) {

        //创建Integer类对象
        int i = 100 ;
        Integer integer = new Integer(i) ;
        System.out.println(integer);
        System.out.println("---------------------");
        //创建一个字符串
       // String s = "hello" ;
        String s  = "50" ;
        Integer integer2 = new Integer(s) ;
        System.out.println(integer2);
    }
}

int—>Integer拆箱装箱:

自动拆装箱,可变参数,静态导入,增强for循环,<泛型>,枚举类
自动拆装箱:

基本类型—> 对应的包装类类型 (装箱)

int---->Integer
对应的包装类型---->基本类型 (拆箱)

public class IntegerDemo3 {
    public static void main(String[] args) {

        //创建Integer类对象
        int i = 100 ;
        Integer ii = new Integer(i) ;
        ii += 200 ;


        System.out.println("ii:"+ii);
        /**
         *通过反编译工具查看
         int i = 100;
         Integer ii = new Integer(i);  //创建Integer类对象
         ii = Integer.valueOf(ii.intValue() + 200);      ii = Integer.valueIf(先拆箱--Integer--->int + 200)
                                            //将300赋值Integer变量ii,底层使用valueOf(int)--->int---->Integer 装箱
         System.out.println((new StringBuilder()).append("ii:").append(ii).toString());//以字符串形式输出出来
         */
    }
}

将int---->String

Integer作为桥梁

String---->int

public class IntegerDemo4 {
    public static void main(String[] args) {

        //int---->String
        int i = 50 ;
        //String result = "" ;
        //result = result + i ;//拼接符号
        //System.out.println(result);//"50"

        //使用功能
        //方式1: Integer类的静态功能
        //public static String toString(int i)
        String str = Integer.toString(i);
        System.out.println(str);
        System.out.println("------------------------");

        //方式2:int---->Integer---->public String toString()
        Integer ii = new Integer(i) ;
        String str2 = ii.toString(); //底层使用的方法public static String toString(int i)
        System.out.println(str2);


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

        //String--->int(使用居多)
        //开发中:浏览器(客户端)---->传递给后端的数据(String类型)
        //方式1:public static int parseInt(String s)throws NumberFormatException:数字字符串 (使用最多)
        //通用方法:String--->long       Long.parseLong(String s)---->long
        // String ----double          Double  public static double parseDouble(String s)
        String s = "100" ;
        int result = Integer.parseInt(s);
        System.out.println(result);

        System.out.println("------------------------------------------");
        //String ---->Integer---->int
        //Integer的构造方法 Integer(String s)
        //Integer 的成员方法:int intValue()--->int
        Integer integer = new Integer(s) ;
        int result2 = integer.intValue();
        System.out.println(result2);

    }
}

$$

$$

/**
 * @Author Kuke
 * @Date 2021/7/28
 *
 * 看程序,写结果
 */
public class IntegerTest {
    public static void main(String[] args) {

        Integer i1 = new Integer(127) ;
        Integer i2 = new Integer(127) ;
        System.out.println(i1==i2);//false
        System.out.println(i1.equals(i2));//true
       System.out.println("----------------------------");
        Integer i3 = 127 ;//valueOf(127)  127  (-128~127)    //直接从内部缓存区中取出数据并么有重新创建对象
        Integer i4 = new Integer(127) ;
        System.out.println(i3== i4);//false
        System.out.println(i3.equals(i4));//true
        System.out.println("-----------------------------");
        Integer i5 = 128 ;  //128已经超出了范围 :new Integer(128)
        Integer i6 = new Integer(128) ;
        System.out.println(i5==i6);
        System.out.println(i5.equals(i6));

        System.out.println("-------------------------------");
        Integer i7 = 127 ;
        Integer i8 = 127 ;
        System.out.println(i7==i8);//true  IntegerCache:缓存区取出数据
        System.out.println(i7.equals(i8));//true

        System.out.println("-------------------------------");
        Integer i9 = 128 ;//  缓存区中范围:-128~127           return new Integer(128)
        Integer i10 = 128 ;
        System.out.println(i9==i10);//false
        System.out.println(i9.equals(i10));//true

      /* Integer i = 127 ;
        System.out.println(i);*/

        /**
         * 翻译工具查看:执行底层的valuOf()
         * Integer i = Integer.valueOf(127);
         * 		System.out.println(i);
         */
    }
}

Charcater :char类型的包装类类型:

构造方法

public Character(char value)
主要了一些功能

public static boolean isUpperCase(char ch):判断当前字符是否大写字母字符

public static boolean isLowerCAse(char ch):是否为小写字母字符

public static boolean isDigit(char ch):是否为数字字符
//String转换的功能很类似

public static char toLowerCase(char ch):将字符转换成小写

public static char toUpperCase(char ch):将字符转换成大写

public class CharacterDemo {
    public static void main(String[] args) {

        //创建字符类对象
        Character character = new Character('a') ;
//        Character character = new Character((char)(97)) ;
        System.out.println(character);

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

        System.out.println("isUpperCase():"+Character.isUpperCase('A'));
        System.out.println("isUpperCase():"+Character.isUpperCase('a'));
        System.out.println("isUpperCase():"+Character.isUpperCase('0'));

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

        System.out.println("isLowerCase():"+Character.isLowerCase('A'));
        System.out.println("isLowerCase():"+Character.isLowerCase('a'));
        System.out.println("isLowerCase():"+Character.isLowerCase('0'));

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

        System.out.println("isDigit():"+Character.isDigit('A'));
        System.out.println("isDigit():"+Character.isDigit('a'));
        System.out.println("isDigit():"+Character.isDigit('0'));

       // char ch = 'a' ;
       // System.out.println(Character.toUpperCase(ch));
    }
}

例题:

 *  输入:
 *       "Hello123World"
 *
 *  输出:
 *          大写字母有2*          小写字母字符:8*          数字字符:3*
 *    分析:
 *          0)定义三个统计变量
 *                  bigCount
 *                  smallCount
 *                  numberCount
 *          1)键盘录入一个字符串
 *          2)
 *                  方式1  获取到每一个字符, 字符对应ASCII码表的值 (太麻烦)
 *          方式2:将字符串转换成字符数组
 *          3)遍历字符数组
 *              获取到每一个字符
 *                  如果当前字符  'A', 'Z'    大写字母字符          bigCount ++
 *                               'a' ,'z'     小写字母字符            smallCount++
 *                               '0','9'        数字字符            numberCount++
 *
 */
public class Test {
    public static void main(String[] args) {

        //定义三个统计变量
        int bigCount = 0  ;
        int smallCount = 0 ;
        int numberCount =  0;
        //创建键盘录入对象
        Scanner sc = new Scanner(System.in) ;

        //提示并录入数据
        System.out.println("请您输入一个数据:");
        String line = sc.nextLine() ;

        //转换成字符数组
        char[] chs = line.toCharArray();
        for (int i = 0; i <chs.length ; i++) {
            char ch = chs[i] ;

         /*   //判断
            if(ch>='A' && ch<='Z'){
                //大写字母
                bigCount ++ ;
            }else if(ch>='a' && ch<='z'){
                //小写字母
                smallCount ++ ;
            }else if(ch >='0' && ch<='9'){
                numberCount ++ ;
            }*/

         //直接判断
            if(Character.isDigit(ch)){
                numberCount ++ ;
            }else if(Character.isUpperCase(ch)){
                bigCount ++ ;
            }else if(Character.isLowerCase(ch)){
                smallCount ++;
            }

        }

        System.out.println("大写字母字符有"+bigCount+"个");
        System.out.println("小写字母字符有"+smallCount+"个");
        System.out.println("数字字符有"+numberCount+"个");
    }
}

日历类:Calendar:

日历类:java.util.Calendar
Calendar:提供一些诸如 获取年,月,月中的日期 等等字段值

抽象类,不能实例化

如果一个类没有抽象方法,这个类可不可以定义为抽象类? 可以,为了不能实例化,通过子类间接实例化
不能实例化:

静态功能,返回值是它自己本身

public static Calendar getInstance()
成员方法:

public int get(int field):根据给定日历字段----获取日历字段的值(系统的日历)
public abstract void add(int field,int amount):给指定的日历字段,添加或者减去时间偏移量

参数1:日历字段

参数2:偏移量

public class CalendarDemo {
    public static void main(String[] args) {

        //创建日历类对象
        //获取系统的年月日
       // Calendar c = new Calendar() ;
        //public static Calendar getInstance()
        Calendar calendar = Calendar.getInstance();
       // System.out.println(calendar);

        //获取年
        //public static final int YEAR
        int year = calendar.get(Calendar.YEAR) ;

        //获取月:
        //public static final int MONTH:0-11之间
        int month = calendar.get(Calendar.MONTH) ;

        //获取月中的日期
        //public static final int DATE
        //public static final int DAY OF MONTH : 每个月的第一天1
        int date = calendar.get(Calendar.DATE) ;

        System.out.println("当前日历为:"+year+"年"+(month+1)+"月"+date+"日");

        System.out.println("------------------------------------------------");
        //获取3年前的今天
        //给year设置偏移量
        // public abstract void add(int field,int amount)
       // calendar.add(Calendar.YEAR,-3);
        //获取
      //  year = calendar.get(Calendar.YEAR) ;
      //  System.out.println("当前日历为:"+year+"年"+(month+1)+"月"+date+"日");

        //5年后的十天前
        //需求:键盘录入一个年份,算出任意年份的2月份有多少天 (不考虑润月)




    }
}

Date:表示特定瞬间,精确到毫秒:

java.util.Date:表示特定瞬间,精确到毫秒!

它还允许格式化和解析日期字符串

构造方法:

public Date():当前系统时间格式

public Date(long date):参数为 时间毫秒值---->Date对象 (1970年1月1日…)

public class DateDemo {
    public static void main(String[] args) {
        //创建日期类对象
        Date date  = new Date() ;
        System.out.println(date);
        //Wed Jul 28 17:32:06 CST 2021 日期对象
        System.out.println("------------------------");

        long time = 60*60 ;
        Date date2 = new Date(time) ;
        System.out.println(date2);
    }
}

java.util.Date-----String 格式化过程
DateForamt:抽象类----提供具体的日期/格式化的子类:SimpleDateFormat

format(Date对象)—>String
SimpleDateFormat:构造函数

public SimpleDateFormat():使用默认模式

public SimpleDateFormat(String pattern):使用指定的模式进行解析或者格式 (推荐)

参数:

一种模式

表示年 “yyyy”

表示月 “MM”

表示月中的日期 “dd”

一天中小时数 “HH”

分钟数 “mm”

秒数 “ss”
String:日期文本----->Date

解析过程
public Date parse(String source)throws ParseException

如果解析的字符串的格式和 public SimpleDateFormat(String pattern)的参数模式不匹配的话,就会出现解析异常!
封装成功工具类DateUtils: 构造方法私有,功能都是静态

第一个将String—Date

将Date—>String

public class DateDemo2 {
    public static void main(String[] args) throws ParseException {
        //Date----->String:格式化
        //1)创建Date对象:表示当前系统时间对象
        Date date  = new Date() ;
        System.out.println(date);
        //2)创建SimpleDateForamt对象:(中间桥梁)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        //3)调用format:格式化
        String strDate = sdf.format(date);
        System.out.println(strDate);



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

        //String---->Date(重点)
        //1)有一个日期文本格式
        //2)创建SimpleDateFormat对象指定一个模式
        //3)调用解析parse方法
        //注意:SimpleDateFormat解析模式必须和String日期文本格式匹配一致
        String source = "2008-5-12" ; //日期文本

        //SimpleDateFormat sdf2  = new SimpleDateFormat("yyyy年MM月dd日") ;
        SimpleDateFormat sdf2  = new SimpleDateFormat("yyyy-MM-dd") ;
        //public Date parse(String source)throws ParseException
        Date dateResult = sdf2.parse(source);
        System.out.println(dateResult);


    }
}

package com.qf.dateutils_01;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Kuke
 * @Date 2021/7/29
 *
 * 这是针对java.util.Date日期对象和String:日期文本字符串进行相互转换的工具类
 */
public class DateUtils {

    //构造方法私有化
    private DateUtils(){}

    //提供两个静态功能
    //Date---->String

    /**
     * 这个方法是针对将日期对象转换成日期文本字符串
     * @param date     需要被格式化的日期对象
     * @param pattern   需要指定的模式
     * @return  返回的日期文本字符串  结果 yyyy-MM-dd
     */
    public static String date2String(Date date,String pattern){
        //分步走
        //创建SimpleDateFormat对象
       /* SimpleDateFormat sdf = new SimpleDateFormat(pattern) ;
        String result = sdf.format(date);
        return  result ;*/

       //一步走
        return new SimpleDateFormat(pattern).format(date) ;
    }


    //String--->Date: 解析过程: parse(String source) throws ParseException

    /**
     * 这个方法针对String日期文本字符串转换成日期对象
     * @param source   需要被解析的日期文本字符串
     * @param pattern   需要解析中使用的一种模式
     * @return  返回的就是日期对象Date
     */
    public static Date string2Date(String source,String pattern) throws ParseException {

        return new SimpleDateFormat(pattern).parse(source) ;
    }
}

Math方法:

java.lang.Math :针对数学运算的工具类,提供了很多方法

public static int abs(int a):绝对值方法

public static double ceil(double a):向上取整

public static double floor(double a):向下取整

public static int max(int a,int b):获取最大值

public static int min(int a,int b):获取最小值

public static double pow(double a,double b):a的b次幂

public static double random():[0.0,1.0):随机数

public static long round(double a):四舍五入

public static double sqrt(double a):开平方根
Math类中的功能都是静态的,里面构造方法私有了!一般情况:工具类中构造方法都是会私有化(自定义的工具类),提供对外静态的公共访问方法

public class MathDemo {
    public static void main(String[] args) {
        //abs()
        System.out.println(Math.abs(-100));
        // public static double ceil(double a):向上取整
        System.out.println(Math.ceil(13.56));
       // public static double floor(double a):向下取整
        System.out.println(Math.floor(12.45));
        // public static int max(int a,int b):获取最大值
        System.out.println(Math.max(Math.max(10,30),50));//方法嵌套
        //public static double pow(double a,double b):a的b次幂
        System.out.println(Math.pow(2,3));
        //ublic static long round(double a):四舍五入
        System.out.println(Math.round(13.78));

        //  public static double sqrt(double a):开平方根
        System.out.println(Math.sqrt(4));

    }
}
package com.qf.random_02;

/**
 * @Author Kuke
 * @Date 2021/7/29
 * JDK5的静态导入特性,必须方法静态的(导入到方法的级别)
 *
 *Math类的功能都是静态的,就可以使用静态导入
 * import static 包名.类名.方法名;
 *
 * 前提不能和其他方法名重名;
 *
 */
import  java.util.Scanner ;//导入到类的级别

import static java.lang.Math.abs ;
import static java.lang.Math.random;


public class MathTest {
    public static void main(String[] args) {

        System.out.println(Math.abs(-100));
       // System.out.println(java.lang.Math.abs(-100)); //默认就是使用当前abs方法,并不是Math提供的
        System.out.println(abs(-100));
        System.out.println(random()*100+1);
    }

    //自定义了方法名abs
    public static int abs(int a){
       // System.out.println(a);
        return a ;
    }

}

产生随机数:

public class RandomDemo {
    public static void main(String[] args) {
        //创建一个随机数生成器
//        public Random(long seed)
//        Random random = new Random(1111) ;

        //每次通过随机数生成器产生的随机不同
        Random random =  new Random() ;
        //产生10个数
        for(int x = 0 ; x < 10 ; x ++){
            // public int nextInt():
//            int num = random.nextInt();

            //public int nextInt(int n)
            int num = (random.nextInt(30)+1);
            System.out.println(num);

        }
    }
}

package com.qf.bigdecimal_03;

import java.math.BigDecimal;

/**
 * @Author Kuke
 * @Date 2021/7/29
 *
 * 小数要进行精确计算-还可以计算的同时保留小数点后的有效位数
 * Java提供的类: BigDecimal
 *
 * 构造方法
 * public BigDecimal(String value):数字字符串
 *
 * 成员方法:
 *      public BigDecimal add(BigDecimal augend)加
 *      public BigDecimal subtract(BigDecimal subtrahend)减
 *      public BigDecimal multiply(BigDecimal multiplicand)乘
 *      public BigDecimal divide(BigDecimal divisor):除
 *
 *      public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)
 *          参数1:商
 *          参数2:小数点后保留的有效位数
 *          参数3:舍入模式 :四舍五入
 */
public class BigDecimalDemo {
    public static void main(String[] args) {
        //System.out.println(1.01 / 0.36);

        //创建BigDecimal对象
        BigDecimal bg1 = new BigDecimal("1.01") ;
        BigDecimal bg2 = new BigDecimal("0.36") ;

        System.out.println("------------------------------------");
        BigDecimal bg3 = new BigDecimal("10.0") ;
        BigDecimal bg4 = new BigDecimal("5.05") ;

        System.out.println(bg1.add(bg2));
        System.out.println(bg1.subtract(bg2));
        System.out.println(bg1.multiply(bg2));
       // System.out.println(bg3.divide(bg4));//不保留(整除)
        System.out.println(bg3.divide(bg4,3,BigDecimal.ROUND_HALF_UP));//四十五入

    }
}

对象数组?:

能够存储对象的数组
需求:

使用数组存储5个学生(姓名,年龄,性别),然后将数组进行遍历,获取出来每一个学生的信息!

分析:

1)创建一个学生类

name,age,gender/sex

  1. 数组存储5个学生

数组的定义格式:

数据类型[] 数组名称 = new 数据类型[长度] ; 学生对象数组

数据类型:Student类型 Student[] students = new Student[5] ;

3)创建5个学生对象:s1,s2,s3,s4,s5

4)students[0] =s1 ; 给数组中的元素进行赋值

students[1] = s2;


5)遍历学生数组,获取学生信息

现在5个学生,以后学生的不断的增加或减少,用数组合适吗? 数组不适合针对长度可变的需求,所以Java提供—

集合框架去使用!

public class ObjectArrayDemo {
    public static void main(String[] args) {

        //创建学生数组
        //  数据类型[] 数组名称 = new 数据类型[长度] ;  学生对象数组
        Student[] students = new Student[5] ;
        //创建5个学生
        Student s1 = new Student("文章",35,"男") ;
        Student s2 = new Student("高圆圆",42,"女") ;
        Student s3 = new Student("刘亦菲",33,"女") ;
        Student s4 = new Student("马蓉",30,"女") ;
        Student s5 = new Student("马保国",65,"男") ;

        //给数组中的元素赋值
        students[0] = s1 ;
        students[1] = s2 ;
        students[2] = s3 ;
        students[3] = s4 ;
        students[4] = s5 ;

        //遍历学生数组
        for(int x = 0 ; x < students.length ; x ++){
            //System.out.println(students[x]);
            //就需要同getXXX()方法获取成员信息
            Student s = students[x] ;
            System.out.println(s.getName()+"---"+s.getAge()+"---"+s.getGender());
        }


    }
}

集合和数组有什么区别:

1)长度区别

数组:长度固定

集合:长度可变
2)存储数据类型的区别

数组:

可以存储基本数据类型,也可以存储引用数据类型

int[] arr = {100,200,50,“hello”} ;不行的
集合:前提条件:集合中加入泛型<> 也是在模拟数组的特点:

只能存储引用类型 Collection :泛型<引用类型>

3)存储元素的区别:

数组:

存储的元素必须为同一种数据类型

举例:

水杯中加入水

集合:如果没有加入泛型 :就出任意类型的元素(必须引用类型)
举例:

水杯加入水,可乐,加入威士忌
Collection:集合层次的根接口,一些集合允许元素重复(List),一些集合不允许元素重复(Set)

一些集合有序(存储和取出一致)(List),一些集合无序(存储和取出不一致)(Set),

JDK不提供此接口的任何直接实现:它提供了更具体的子接口的实现,如Set和List

Collection

List

最具体的子实现类ArrayList,LinkedList,Vector

基本功能:

添加

boolean add(Object e):添加元素 E(Element)

删除:

void clear() 暴力删除(将集合的素有元素全部干掉)

boolean remove(Object o):从集合中删除指定的元素

获取集合的元素数 :int size()

判断功能:boolean isEmpty():判断集合是否为空,为空元素,则返回true

boolean contains(Object o):判断集合中是否包含指定元素,包含则返回true

public class CollectionDemo {
    public static void main(String[] args) {

        //创建Collection集合对象
        //接口多态
        Collection c = new ArrayList() ;
        System.out.println(c);//ArrayList重写了Object的toString()方法

        System.out.println("-----------------------------------------");
        // boolean add(Object e):添加元素  E(Element)
     //   boolean flag = c.add("hello");
        /**
         * 添加的原码
         * public boolean add(E e) {
         *         ensureCapacityInternal(size + 1);  // Increments modCount!!
         *         elementData[size++] = e;
         *         return true;  //永远返回true
         *     }
         */
        //System.out.println(flag);
        c.add("hello") ;
        c.add(100) ;
        c.add("javaee") ;
        System.out.println(c);
        //   void clear()
//        c.clear();

        // boolean remove(Object o):从集合中删除指定的元素
      //  System.out.println(c.remove(100));

        //int size()
        System.out.println(c.size());
        System.out.println("--------------------------");
        System.out.println(c.contains("world"));
        System.out.println(c.contains("javaee"));
        System.out.println(c.isEmpty());

        System.out.println(c);
    }
}

Collection的高级功能
boolean addAll(Collection c):添加一个集合中的所有元素

boolean containsAll(Collection c):包含一个集合中的所有元素
boolean removeAll(Collection c):删除集合中的所有元素, (删除一个算删除,还是删除所有)
boolean retainAll(Collection c):A集合对B集合求交集, boolean的返回值是什么意思,交集的元素是保存在A中还是B中

//Collection最基本的遍历功能,不属于集合的专有遍历

Object[] toArray():将集合转换成了对象数组

public class CollectionDemo2 {
    public static void main(String[] args) {

        //创建两个Collection集合对象
        Collection c1 = new ArrayList() ;
        c1.add("abc1") ;
        c1.add("abc2") ;
        c1.add("abc3") ;
        c1.add("abc4") ;
       /* c1.add("abc5") ;
        c1.add("abc6") ;
        c1.add("abc7") ;*/
      /*  c1.add("abc5") ;
        c1.add("abc6") ;
        c1.add("abc7") ;*/
        Collection c2 = new ArrayList() ;
        c2.add("abc1") ;
        c2.add("abc2") ;
        c2.add("abc3") ;
        c2.add("abc4") ;
        c2.add("abc5") ;
        c2.add("abc6") ;
        c2.add("abc7") ;
        System.out.println(c1);
        System.out.println(c2);
        System.out.println("---------------------------------");

        //boolean addAll(Collection c):添加一个集合中的所有元素
       // System.out.println(c1.addAll(c2));
        //boolean containsAll(Collection c) :包含所有的元素算包含...
      //  System.out.println(c1.containsAll(c2));

        //boolean removeAll(Collection c):删除集合中的所有元素, (删除一个算删除,还是删除所有):删除一个算删除(必须同时都被包含进去)
       // System.out.println(c1.removeAll(c2));

        // boolean retainAll(Collection c):A集合对B集合求交集, boolean的返回值是什么意思,交集的元素是保存在A中还是B中

        /**
         * A集合堆B集合求交集,交集的元素存储在A集合中,然后返回值的意思: 看A集合的元素是否有变化(之前的元素和现在交集的元素进行对比)
         * 如果有变化,返回true;没有变化,则返回false
         *
         */

        System.out.println(c1.retainAll(c2)); //c1集合对c2集合取交集
        System.out.println(c1);
        System.out.println(c2);

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

        //使用Colllection存储5个学生(姓名,年龄,性别),然后将Collection进行遍历,获取出来每一个学生的信息!
        //创建一个Collection集合对象
        Collection c = new ArrayList() ;

        //创建5个学生
        Student s1 = new Student("宋江",45,"男") ;
        Student s2 = new Student("李逵",35,"男") ;
        Student s3 = new Student("武大郎",35,"男") ;
        Student s4 = new Student("西门庆",30,"男") ;
        Student s5 = new Student("吴用",40,"男") ;

        //存储集合中
        c.add(s1) ;
        c.add(s2) ;
        c.add(s3) ;
        c.add(s4) ;
        c.add(s5) ;

        //  Object[] toArray():将集合转换成了对象数组
        Object[] objs = c.toArray();//数组存储的每一个数据类型 Object obj = new Student() ; //向上转型
        //遍历数组
        for(int x = 0 ; x < objs.length ; x ++){
            //System.out.println(objs[x]) ;
            //getXXX()---->Student类的方法

            Student student = (Student) objs[x]; //向下转型
            System.out.println(student.getName()+"---"+student.getAge()+"---"+student.getGender());
        }


    }
}

Collection的迭代器:集合的专有遍历方式

Iterator iterator():返回值类型接口类型,需要返回的子实现类对象

Iterator接口:

boolean hasNext():判断迭代器中是否存在下一个元素

Object next(): 获取下一个可以遍历的元素

给Collection中存储String类型,遍历出来

public class CollectionTest {
    public static void main(String[] args) {

        //创建集合对象
        Collection c = new ArrayList() ; //List接口的子实现类 (重复元素)

        //添加元素
        c.add("hello") ;
        c.add("world") ;
        c.add("javaee") ;
       // System.out.println(c);

        //获取Collection的迭代器Iterator iterator()
        Iterator it = c.iterator();
        //第一次获取
        //Object next():  获取下一个可以遍历的元素
        /*if(it.hasNext()){
            Object obj = it.next();
            System.out.println(obj);
        }


        //第二次获取
        if(it.hasNext()){
            System.out.println(it.next());
        }


        //第三次获取
        if(it.hasNext()){
            System.out.println(it.next());
        }


        //第四次获取
      //  System.out.println(it.next());//此时没有元素了,要是用迭代器去获取元素,就会出现这个问题!
        //加入判断
        if(it.hasNext()){
            System.out.println(it.next());
        }*/

        //如果现在明确存储了3个元素,以后这些数据可能数据库获取的一个列表集合数据,一般while循环
        while(it.hasNext()){//判断迭代器中有下一个元素
            //才获取
            Object obj = it.next();// Object obj = new String("hello") ...
            //  System.out.println(obj+"----"+obj.length());
            //获取的元素同时,还要获取当前存储元素的长度  ---->String类型   length()
            String str = (String) obj;//向下转型
            System.out.println(str+"----"+str.length());
        }

    }
}
package com.qf.collection_06;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @Author Kuke
 * @Date 2021/7/29
 *  需求:
 *    使用Collection存储4个学生(姓名和年龄),然后使用Iterator iterator()
 *  迭代器遍历Collection集合中的元素,获取4个学生信息(要调用是getXXX()获取)
 *
 *
 */
public class CollectionTest2 {
    public static void main(String[] args) {
        //创建集合对象
        Collection c = new ArrayList();

        //创建4个学生
        Student s1 = new Student("诸葛亮",45) ;
        Student s2 = new Student("庞统",30) ;
        Student s3 = new Student("周瑜",35) ;
        Student s4 = new Student("吕布",25) ;

        c.add(s1) ;
        c.add(s2) ;
        c.add(s3) ;
        c.add(s4) ;
      //  c.add("hello") ;

        //获取迭代器
        Iterator iterator = c.iterator();
        while(iterator.hasNext()){
//            Object obj = iterator.next();
            Object obj = iterator.next();
            // System.out.println(obj);
//            String s = (String)obj  ;
//            System.out.println(s);
            Student s = (Student)obj ;
            System.out.println(s.getName()+"---"+s.getAge());


        }

    }
}

泛型的格式:

<引用数据类型>

模拟数组创建的时候,就已经明确了数据类型

举例:

// String[] array = {“hello”,“world”,“java”,100}

创建集合对象的时候,明确了集合中存储的数据类型<>

集合类型<引用数据类型> 集合对象名 = new 子实现类<引用数据类型>() ;

泛型的好处:

1)将运行时期异常提前了编译时期

2)避免了强制类型转换

3)提高了程序安全性

使用Collection集合存储5个学生,加入泛型 Collection,使用迭代器遍历并获取

public class GenericDemo {
    public static void main(String[] args) {

        //创建Collection集合对象
        Collection<String> c = new ArrayList<String>() ; //new XXX<数据类型>: jdk7以后泛型推断


        c.add("hello") ;
        c.add("高圆圆") ;
        c.add("你好吗") ;
       // c.add(100) ;

        //获取迭代器Iteratr<E>是集合中存储的泛型是一致的
        Iterator<String> it = c.iterator();
        while(it.hasNext()){
            //获取String字符串的同时,还要获取长度
            String str = it.next();
            System.out.println(str+"---"+str.length());
        }
    }
}

List:

List接口继承Collection

List集合特点:

有序(存储元素和取出元素一致)

允许元素重复
具备Collection相关的功能

Object [] toArray()

Iterator iterator()

特有功能

void add(int index,Object element):在指定的索引处插 入元素

Object get(int index):获取指定位置处的元素 + int size():一种新的集合遍历方式

Object remove(int index):删除指定位置处的元素

Object set(int index,E element):修改指定位置处的元素(替换)
ListIterator listIterator():列表迭代器

ListIterator接口:

void add(E e)有添加

remove():有删除

public class ListDemo {

    public static void main(String[] args) {
        //创建List集合对象
        List<String> list = new ArrayList<String >();

        //添加元素
        list.add("hello") ;
        list.add("hello") ;
        list.add("world") ;
        list.add("world") ;
        list.add("world") ;
        list.add("javaEE") ;
        list.add("javaEE") ;

        // void add(int index,Object element):在指定的索引处插 入元素

        list.add(1,"高圆圆");
        //Object get(int index):获取指定位置处的元素 :返回的被获取到的元素内容
        System.out.println(list.get(1));

        //  Object remove(int index):删除指定位置处的元素,返回被删除的元素
        System.out.println(list.remove(2));
        System.out.println("---------------------------------------");

        //Object set(int index,E element):修改指定位置处的元素(替换)
        System.out.println(list.set(1,"赵又廷"));
        System.out.println(list);
    }
}

List集合的遍历方式

Object[] toArray()

Iterator iterator()

Object get(int index):获取指定位置处的元素 + int size():一种新的集合遍历方式
ListIterator listIterator():列表迭代器 :List集合专有遍历方式

存储String,并进行遍历
//<?>:任意类型包括Object <? extends E> <? super E> 泛型高级:通配符

public class ListTest {
    public static void main(String[] args) {

        //创建List集合对象
        List<String> list = new ArrayList<>() ;

        //添加元素
        list.add("hello");
        list.add("world");
        list.add("java");
        list.add("android");

        //size()+get(int index)集合
        for(int x = 0 ; x < list.size() ; x ++){
            String s = list.get(x);
            System.out.println(s+"---"+s.length());
        }

        System.out.println("-----------------------------------------------");
        //List集合存储Student对象并进行遍历(学生:姓名,年龄)
        List<Student> stuList = new ArrayList<>() ;//JDK7以后 泛型推断:自动的和前面的泛型类型一致!

        //创建3个学生
        Student s1 = new Student("张佳宁",31) ;
        Student s2 = new Student("迪丽热巴",29) ;
        Student s3 = new Student("张俊杰",20) ;

        //添加到列表中
        stuList.add(s1) ;
        stuList.add(s2) ;
        stuList.add(s3) ;

        //遍历
        //方式1:Object[] toArray()
        Object[] objs = stuList.toArray();
        for(int x = 0 ; x < objs.length ; x ++){
            Student s = (Student) objs[x];
            System.out.println(s.getName()+"----"+s.getAge());
        }


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

        //Collection的迭代器
        Iterator<Student> it = stuList.iterator();
        while(it.hasNext()){
            Student s = it.next() ;
            System.out.println(s.getName()+"---"+s.getAge());
           // System.out.println((it.next().getName()+"---"+(it.next().getAge())));
            // next()只能使用一次,不能多次使用 //错误的用法
        }
        System.out.println("-------------------------------------");

        //方式3:size()+get(int index)
        for(int x = 0 ; x < stuList.size() ; x ++){

            Student s = stuList.get(x);
            System.out.println(s.getName()+"----"+s.getAge());
        }


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

        //正向遍历:ListIterator<E> listIterator():列表迭代器  :List集合专有遍历方式
        ListIterator<Student> lit = stuList.listIterator();
        /**
         * ListIterator extends Iterator{}
         *
         * class ArrayList{
             *  List具体ArrayList子实现类重写了Iterator listiterator(){
             *
             *      return new ListItr(0) ;
             *  }
         *
         *          private class ListItr extends Itr implements Iterator{
         *
         *                      //具备hasNext()
         *                      //next()
         *          }
         *
         *  }
         */
        while(lit.hasNext()){
            Student student = lit.next();
            System.out.println(student.getName()+"---"+student.getAge());
        }

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

        //逆向遍历:前提:必须有正向遍历
        //ListIterator<E> listIterator()
        //ListIterator:特有功能:
        //boolean hasPrevious():是否有上一个元素可以迭代
        //Object previous():获取上一个元素
        while(lit.hasPrevious()){
            Student student = lit.previous();
            System.out.println(student.getName()+"---"+student.getAge());
        }

    }
}

package com.qf.list_01;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * @author Kuke
 * @date 2021/7/30
 *
 * 需求:
 *      通过List集合ArrayList集合对象,如果当前集合中存在"world"元素,那么就给集合中添加一个"javaEE"元素,最后将
 *      集合中的所有元素进行遍历!
 *     举例:
 *          List集合现在就存有三个元素
 *      "hello"
 *      "world"
 *      "java"
 *
 *
 *   java.util.ConcurrentModificationException:并发修改异常
 *
 *   集合在使用迭代器会经常出现的问题:并发修改异常,
 *          当集合的元素正在被迭代器进行遍历,那么集合对象是不能够对元素进行增加或者删除 (一个线程正在遍历,一个线程在修改元素)
 *
 * 解决方案:
 *      1)要么就是迭代器去遍历集合的元素,迭代器去添加元素  :列表迭代器才具备添加的动作
 *      2)要么集合遍历,集合添加
 *
 */
public class ListTest2 {
    public static void main(String[] args) {

        //创建List集合对象
        List<String> list = new ArrayList<>() ;

        //给添加元素
        list.add("hello") ;
        list.add("world") ;
        list.add("javaee") ;

        //使用迭代器遍历
        //Iterator iterator()
      /*  Iterator<String> it = list.iterator();  //"hello","world","javaee"
        while(it.hasNext()){
            String s = it.next() ;//"hello","world","javaee"

            //判断
            if("world".equals(s)){
                list.add("javaEE") ;//集合对象添加的元素,迭代器不知道
            }
        }

        System.out.println(list);*/

      //解决方案1:  1)要么就是迭代器去遍历集合的元素,迭代器去添加元素  :列表迭代器才具备添加的动作
        //ListIterator
        //void add(E e)
        /*ListIterator<String> lit = list.listIterator();
        while(lit.hasNext()){
            //获取
            String s = lit.next();
            //判断是否存在"world"元素
            if("world".equals(s)){
                //列表迭代器添加
                lit.add("javaEE");
            }
        }*/

        //方案2:要么集合遍历,集合添加
        //size()+get(int index)
        for(int x = 0 ; x < list.size(); x ++){
            String s = list.get(x);
            if("world".equals(s)){//将常量放前面,防止出现NullPointerException
                list.add("javaEE");
            }
        }
        System.out.println(list);

    }
}

增强for:

JDK5以后 提供了增强for循环,替代集合中迭代器去遍历集合使用的(优先在集合中使用)
格式:

for(存储的引用数据类型 变量名: 集合/数组对象){ //集合使用居多,数组一般都是使用普通for

使用变量名即可

注意事项:

当前集合对象不能为空 null :foreach语句:增强for它本身就是获取迭代器了,就会出现空指针异常

public class ForeachDemo {

    public static void main(String[] args) {

        //数组
        int[] arr = {11,22,33,44,55} ;
        for(int x  = 0 ; x < arr.length ; x ++){
            System.out.println(arr[x]);
        }
        System.out.println("--------------------------------");

        /*
        for(存储的引用数据类型 变量名: 集合/数组对象){
        *            使用变量名即可
                    *      }

         */
        //对于数组来说:使用普通for
       /* for(int a:arr){
            System.out.println(a);
        }*/

       //创建List集合
        List<String> list = new ArrayList<>() ;
        list.add("hello") ;
        list.add("world") ;
        list.add("javaee") ;

       /* for(String s:list){//替换迭代器使用
            //如果存在world元素,添加一个android元素
            //System.out.println(s);

            if("world".equals(s)){
                list.add("android") ;//出现并发修改异常
            }
           }
           System.out.println(list);
        */

       list = null ;
       if(list!=null){
           for(String s:list){//获取迭代器
               System.out.println(s+"---"+s.length());
           }
       }else{
           System.out.println("当前集合对象为null了");
       }


    }
}
package com.qf.foreach_02;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kuke
 * @date 2021/7/30
 * 需求:
 *        使用增强for遍历List<Student>,存储三个学生,遍历后获取学生信息(姓名和年龄)
 */
public class ForeachTest {

    public static void main(String[] args) {

        //创建List
        List<Student> list = new ArrayList<>() ;
        //创建三个学生
        Student s1  = new Student("张佳宁",29) ;
        Student s2  = new Student("邓超",40) ;
        Student s3  = new Student("黄海波",30) ;

        list.add(s1) ;
        list.add(s2) ;
        list.add(s3) ;
        //方式5:增强for循环
        for (Student s: list) {
//           System.out.println(s.getName()+"---"+s.getAge());
            System.out.println(s); //对象名称:直接使用重写后的toString()
        }
    }
}

package com.qf.list_test_03;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Kuke
 * @date 2021/7/30
 *
 * 产生1-30随机数 (6个)将偶数添加到List集合中
 *
 *    分析:
 *          1)使用随机数生成器Random()
 *          2)创建一个List集合  使用子实现类:ArrayList<Integer>
 *          3)循环for 0-6
 *              1-30之间的随机数 Random成员方法  int nextInt(int n)
 *          4) 如果能够被2整除,添加集合中
 *
 *
 *
 *
 *
 */
public class ListTest {
    public static void main(String[] args) {

        //创建随机生成器对象
        Random random = new Random() ;
        //创建List集合里面Integer类型
        List<Integer> list = new ArrayList<>() ;

        //产生6个1-30之间的随机数
        for(int x = 0 ; x <6 ; x ++){//0,1,2,3,4,5
            //获取随机数
            int num = random.nextInt(30)+1 ;

            //确定偶数
            if(num % 2 == 0){
                //给集合中添加数据
                list.add(num) ;
            }
        }
        //遍历集合
        for(Integer i : list){
            System.out.println(i);
        }
    }
}

List集合如何去重?
方式1:新建空集合思想

存储字符串类型并保证集合的元素唯一!

List
集合中Collection/List—>contains(Object o)底层依赖于Object的equals方法

而List现在存储的是String类型,本身重写Object的equals,所以比较的是内容是否相同

public class ListTest2 {
    public static void main(String[] args) {

        //创建List集合
        List<String> list = new ArrayList<>() ;

        //现在给集合中添加重复的字符串数据
        list.add("hello") ;
        list.add("hello") ;
        list.add("world") ;
        list.add("world") ;
        list.add("javaEE") ;
        list.add("world") ;
        list.add("javaEE") ;
        list.add("android") ;
        list.add("android") ;
        list.add("ios") ;

        //新建一个空的集合List
        List<String> newList = new ArrayList<>() ;
        //遍历以前的集合
        for(String s :list){
            //使用新集合判断,不包含这个元素,说明该元素没有重复,就可以添加
            if(!newList.contains(s)){
                newList.add(s) ;
            }
        }
        //遍历新的集合
        for(String s:newList){
            System.out.println(s);
        }





    }
}

List集合如何去重?

条件:不重新新建一个List集合 ,如何完成?
方式2:利用选择排序的思想去完成

选择排序的思想:

使用0角标对应的元素依次和后面角标对应的元素进行比较,小的往前方法.依次这样比较,1角标,2角标…
List集合—集合列表角标从0开始

遍历当前集合

然后使用0角标对应的元素依次和后面对应的元素进行比较,如果后面的元素和前面的相同了,那么将后面的元素删除掉

角标–

//方式一
public class ListTest3 {
    public static void main(String[] args) {
        //创建List集合
        List<String> list = new ArrayList<>() ;

        //现在给集合中添加重复的字符串数据
        list.add("hello") ;
        list.add("hello") ;
        list.add("world") ;
        list.add("world") ;
        list.add("javaEE") ;
        list.add("world") ;
        list.add("javaEE") ;
        list.add("android") ;
        list.add("android") ;
        list.add("ios") ;

        //利用选择排序的思想完成
        for(int x = 0 ; x < list.size()-1 ; x ++){
            for(int y = x +1 ; y < list.size() ; y++){
                //如果后面的元素和前面的元素相同
                if(list.get(y).equals(list.get(x))){
                    //通过集合remove掉
                    list.remove(y) ; // public Object remove(int index)
                    //角标--
                    y -- ;
                }




            }
        }

        for(String s:list){
            System.out.println(s);
        }

    }
}

//方式二
package com.qf.list_test_03;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kuke
 * @date 2021/7/30
 *
 *
 * List<Student>存储自定义对象 怎么去重?
 *
 *  Student s1 = new Student("高圆圆",42) ;
 *  Student s2 = new Student("高圆圆",42) ;
 *  成员信息如果一致,认为是同一个人,需要使用List集合去重!
 *
 *  方式1:
 *    新建集合思想
 *
 *    contains(Object)方法依赖于Object的equals方法,所以集合存储的类型所在的类必须重写equals方法,否则默认使用
 *    Object的equals方法比较的地址值是否相同!
 *
 *
 * 方式2:使用选择排序思想 将List<Student>存储的重复的学生对象进行重写!
 */
public class ListTest4 {
    public static void main(String[] args) {

        //创建一个List集合
        List<Student> list = new ArrayList<>() ;

        //创建一些学生对象:有重复的成员信息
        Student s1 = new Student("高圆圆",42) ;
        Student s2 = new Student("高圆圆",42) ;
        Student s3 = new Student("刘诗诗",39) ;
        Student s4 = new Student("刘诗诗",39) ;
        Student s5 = new Student("张佳宁",30) ;
        Student s6 = new Student("文章",36) ;
        Student s7 = new Student("文章",36) ;
        Student s8 = new Student("姚笛",32) ;

        //添加到集合中
        list.add(s1) ;
        list.add(s2) ;
        list.add(s3) ;
        list.add(s4) ;
        list.add(s5) ;
        list.add(s6) ;
        list.add(s7) ;
        list.add(s8) ;


        //方式1:创建新的一个新集合
        List<Student> newList = new ArrayList<>() ;
        //遍历以前的集合获取每一个学生对象
        for(Student s:list){
            //如果当前newList不包含这个学生添加到新集合中
            if(!newList.contains(s)){
                newList.add(s) ;
            }
        }

        //遍历新集合
        for(Student student:newList){
            System.out.println(student.getName()+"----"+student.getAge());
        }


    }
}

Vector集合特有功能:

添加

public void addElement(Object obj):在vector对象的末尾添加元素 ------> 一直使用的add(Object e)

删除
public boolean removeElement(Object obj):删除元素

获取功能

public Object elementAt(int index):获取指定位置的元素---->类似于 public Object get(int index)
public Enumeration elements() :Vector集合的专有遍历方式---->类似于 Iterator literator()

接口

boolean hasMoreElements():判断是否有更多的元素可以迭代

Object nextElement() 获取元素

public class VectorDemo {
    public static void main(String[] args) {

        //创建Vector集合对象
        Vector<String> v = new Vector<>() ;

        v.addElement("hello");
        v.addElement("world");
        v.addElement("SpringBoot");
        v.addElement("SpringCloud") ;

        //遍历:特有功能
        Enumeration<String> en = v.elements(); //相当于Iterator
        while(en.hasMoreElements()){
            String s = en.nextElement();
            System.out.println(s+"---"+s.length());
        }

        System.out.println("----------------------------------");
        for(String s: v){
            System.out.println(s+"----"+s.length());
        }

    }
}

插入排序 :

插入排序 时间复杂度:O(N^2)
核心思想:使用1角标对应的元素进行和0角标比较

如果前面元素大,向右移动,确定角标1对应的元素的位置,再次使用2角标对应的元素依次和1和0都元素比较
依次这样比较…

Integer类:包含了int类型的值:

Integer实现自然排序(默认升序排序)
public int compareTo(Integer anotherInteger) { // 8 34

return compare(this.value, anotherInteger.value);

8,34

}

8 34

public static int compare(int x, int y) { //提高程序的执行效率

return (x < y) ? -1 : ((x == y) ? 0 : 1);

}

public class InsertSortTest {

    public static void main(String[] args) {

        //定义一个Integer数组: Integer实现的自然排序:元素能够按照升序默认排序
        Integer[] arr = {34,8,64,51,32,21} ;

        System.out.println("排序前:");
        printArr(arr);

        //定义一个功能
        insertSort(arr) ;
        System.out.println("排序后:");
        printArr(arr);

    }
    //插入排序
    private static void insertSort(Integer[] arr) {

        //定义一个变量j
            int j ; //j记录当前角标的变化
            //定义变量 : p:表示一个比较次数 p=1,2,3,4,5 (每一移动的元素的位置)
            for(int p = 1 ; p < arr.length ; p ++ ){ //比较次数     p=2
                //定义临时变量temp
                Integer temp = arr[p] ;    //temp = 8;          temp = 64
                //开始比较
                for(j = p ; j>0 && temp.compareTo(arr[j-1])<0; j-- ){  // j= 1 ; 1>0&& 8 < 34   j-- : j= 0
                    //j=2 ; 2>0 && 64 < 32
                    //数据移动
                    arr[j] = arr[j-1] ;
                }

                //确定temp的位置:8的位置   64的位置:p=2
                arr[j] = temp ;         // 没有移动

        }

    }

    public static void printArr(Integer[] arr){
        System.out.print("[");
        for(int x = 0 ; x < arr.length ; x ++){
            if(x == arr.length -1){
                System.out.println(arr[x] +"]");
            }else{
                System.out.print(arr[x]+", ");
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值