[Java-05] Commonly used APIs, regular expressions, and collections

main content

  • BigInteger class
  • BigDecimal class
  • Arrays class
  • Packaging
  • Common methods of the String class
  • regular expression
  • Collection set

1 BigInteger class

1.1 Overview

  • Overview: The java.math.BigInteger class is a reference data type that can be used to calculate some large integers. BigInteger can be used when the integer operation exceeds the data range of the basic data type.

1.2 Construction method

  • Construction method: Convert the string of integers to an object of type BigInteger

1.3 Member methods

  • method declaration describe
    public BigInteger add (BigInteger value) Very large integer addition operation
    public BigInteger subtract (BigInteger value) very large integer subtraction
    public BigInteger multiply (BigInteger value) Very large integer multiplication
    public BigInteger divide (BigInteger value) Very large integer division operation, the integer part cannot be divided
package com.bn.api_demo.biginteger_demo;

import java.math.BigInteger;

/*
    构造方法 :
        BigInteger(String value)	可以将整数的字符串,转换为BigInteger对象
    成员方法 :
        public BigInteger add (BigInteger value)	    超大整数加法运算
        public BigInteger subtract (BigInteger value)	超大整数减法运算
        public BigInteger multiply (BigInteger value)	超大整数乘法运算
        public BigInteger divide (BigInteger value)	超大整数除法运算,除不尽取整数部分

 */
public class BigIntegerDemo {
    
    
    public static void main(String[] args) {
    
    
        // 获取大整数对象
        BigInteger bigInteger1 = new BigInteger("2147483648");
        // 获取大整数对象
        BigInteger bigInteger2 = new BigInteger("2");
        // public BigInteger add (BigInteger value)	    超大整数加法运算
        BigInteger add = bigInteger1.add(bigInteger2);
        System.out.println(add);

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

        // public BigInteger subtract (BigInteger value)	超大整数减法运算
        BigInteger subtract = bigInteger1.subtract(bigInteger2);
        System.out.println(subtract);

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

        // public BigInteger multiply (BigInteger value)	超大整数乘法运算
        BigInteger multiply = bigInteger1.multiply(bigInteger2);
        System.out.println(multiply);

        System.out.println("=============");
        // public BigInteger divide (BigInteger value)	超大整数除法运算,除不尽取整数部分
        BigInteger divide = bigInteger1.divide(bigInteger2);
        System.out.println(divide);
    }
}

2 BigDecimal class

2.1 Overview

  • Overview: java.math.BigDecimal can operate on large floating-point numbers to ensure the accuracy of operations. When float and double are stored and calculated, the precision of the data will be lost. If you want to ensure the accuracy of the operation, you need to use BigDecimal.

2.2 Construction method

  • Construction method :
    • public BigDecimal(String val) : Converts the string representation of a BigDecimal to a BigDecimal

2.3 Member methods

  • Member method:

    • method declaration describe
      public BigDecimal add(BigDecimal value) Addition
      public BigDecimal subtract(BigDecimal value) Subtraction
      public BigDecimal multiply(BigDecimal value) Multiplication
      public BigDecimal divide(BigDecimal value) Division operation (there will be exceptions if there is no division)
      public BigDecimal divide(BigDecimal divisor, int roundingMode) Division operation (indivisible, use this method) parameter description: scale exact number of digits, roundingMode rounding mode BigDecimal.ROUND_HALF_UP rounding BigDecimal.ROUND_FLOOR tail removal method BigDecimal.ROUND_UP rounding method
package com.b.api_demo.bigdecimal_demo;

import java.math.BigDecimal;

/*
    构造方法 :
        public BigDecimal(String val)	将 BigDecimal 的字符串表示形式转换为 BigDecimal
    成员方法 :
        public BigDecimal add(BigDecimal value)	加法运算
        public BigDecimal subtract(BigDecimal value)	减法运算
        public BigDecimal multiply(BigDecimal value)	乘法运算
        public BigDecimal divide(BigDecimal value)	除法运算(除不尽会有异常)
        public BigDecimal divide(BigDecimal value, int scale, RoundingMode roundingMode)	除法运算(除不尽,使用该方法)
        参数说明:
        scale 精确位数,
        roundingMode取舍模式
                   BigDecimal.ROUND_HALF_UP 四舍五入
                   BigDecimal.ROUND_FLOOR 去尾法
                   BigDecimal.ROUND_UP  进一法
 */
public class BigDecimalDemo {
    
    
    public static void main(String[] args) {
    
    
        BigDecimal bigDecimal1 = new BigDecimal("0.1");
        BigDecimal bigDecimal2 = new BigDecimal("0.2");

        // public BigDecimal add(BigDecimal value)	加法运算
        BigDecimal add = bigDecimal1.add(bigDecimal2);
        System.out.println(add);

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

        // public BigDecimal subtract(BigDecimal value)	减法运算
        BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
        System.out.println(subtract);

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

        // public BigDecimal multiply(BigDecimal value)	乘法运算
        BigDecimal multiply = bigDecimal1.multiply(bigDecimal2);
        System.out.println(multiply);

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

        // public BigDecimal divide(BigDecimal value)	除法运算(除不尽会有异常)
        // BigDecimal divide = bigDecimal1.divide(bigDecimal2);
        // System.out.println(divide);

        /*
            public BigDecimal divide(BigDecimal divisor, int roundingMode)	除法运算(除不尽,使用该方法)
            参数说明:
            scale 精确位数,
            roundingMode : 取舍模式
                       BigDecimal.ROUND_HALF_UP 四舍五入
                       BigDecimal.ROUND_FLOOR 去尾法
                       BigDecimal.ROUND_UP  进一法
        */

        // BigDecimal divide = bigDecimal1.divide(bigDecimal2, 3, BigDecimal.ROUND_HALF_UP);
        // BigDecimal divide = bigDecimal1.divide(bigDecimal2, 3, BigDecimal.ROUND_FLOOR);
        // BigDecimal divide = bigDecimal1.divide(bigDecimal2, 3, BigDecimal.ROUND_UP);
        // System.out.println(divide);

    }
}

3 Arrays class

3.1 Overview

  • Overview: java.util.Arrays is a tool class for arrays, which contains many static methods for operating on arrays (such as sorting and searching), and also contains a static factory that can convert arrays into List collections (will be mentioned later collective knowledge

3.2 Construction method

  • Construction method: private Arrays(){}

  • public static void sort(int[] a) Arranges the specified array in numerical order
    public static String toString(int[] a) Returns a string representation of the contents of the specified array
package com.bn.api_demo.arrays_demo;

import java.util.Arrays;
import java.util.Random;

/*
    1 随机生成10个[0,100]之间的整数,放到整数数组中,按照从小到大的顺序排序并打印元素内容。
 */
public class ArraysDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建数组
        int[] arr = new int[10];

        // 创建随机数对象
        Random r = new Random();

        // 采用随机数给数组的每一个元素赋值
        for (int i = 0; i < arr.length; i++) {
    
    
            arr[i] = r.nextInt(101);
        }

        // 对数组进行排序
        Arrays.sort(arr);

        // 把数组转成指定格式的字符串
        System.out.println(Arrays.toString(arr));
    }
}

4 packaging

4.1 Overview

  • Overview :
    • The reference data type corresponding to the basic data type in Java

4.2 The role of packaging classes

  • The role of the packaging class:
    • Basic data types, no variables, no methods, the wrapper class is to let the basic data types have variables and attributes, and realize object-oriented interaction
    • Conversion between primitive data types and strings

4.3 Correspondence between basic data types and packaging classes

  • Correspondence between basic data types and wrapper classes
    basic data type type of packaging
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double
    char Character
    boolean Boolean

4.4 Autoboxing and autounboxing

  • Automatic transformation and automatic unboxing

    • Automatic boxing and unboxing started in JDK1.5
    • Autoboxing: Basic data types are automatically converted into corresponding packaging class types
    • Automatic unboxing: the packaging class type is automatically converted into the corresponding basic data type
    Integer i1 = 10;
    int i2 = i1;
    

4.5 Conversion between basic data types and strings

  • Use wrapper classes to convert between basic data types and strings

    • During the development process, data exists in the form of strings when they are transmitted between different platforms. Some data represent numerical meanings. If they are to be used for calculations, we need to convert them to basic data types.

    • Basic data type –> String

      • Add an empty string directly after the value
      • Through the String class static method valueOf()
    • String --> basic data type

      • public static byte parseByte(String s): converts the string parameter to the corresponding byte basic type.
        public static short parseShort(String s): converts the string parameter to the corresponding short basic type.
        public static int parseInt(String s): converts the string parameter to the corresponding int basic type.
        public static long parseLong(String s): converts the string parameter to the corresponding long basic type.
        public static float parseFloat(String s): converts the string parameter to the corresponding float basic type.
        public static double parseDouble(String s): converts the string parameter to the corresponding double basic type.
        public static boolean parseBoolean(String s): converts the string parameter to the corresponding boolean basic type.
  • Precautions :

    • 包装类对象的初始值为null(是一个对象)

    • Java中除了float和double的其他基本数据类型,都有常量池

      • 整数类型:[-128,127]值在常量池
      • 字符类型:[0,127]对应的字符在常量池
      • 布尔类型:true,false在常量池
    • 在常量池中的数据 , 会进行共享使用 , 不在常量池中的数据会创建一个新的对象

5 String类的常用方法

5.1 常用方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9rRiwakS-1683635543379)(.\img\image-20210404212729376.png)]

package com.bn.api_demo.string_demo;

/*
    已知字符串,完成需求
    String str = "I Love Java, I Love Heima";
    判断是否存在  “Java”
    判断是否以Heima字符串结尾
    判断是否以Java开头
    判断 Java在字符串中的第一次出现位置
    判断  itcast 所在的位置

 */
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String str = "I Love Java, I Love Heima";

        // 判断是否存在  “Java”
        System.out.println(str.contains("Java"));// true

        // 判断是否以Heima字符串结尾
        System.out.println(str.endsWith("Heima"));// true

        // 判断是否以Java开头
        System.out.println(str.startsWith("Java"));// false

        // 判断 Java在字符串中的第一次出现位置
        System.out.println(str.indexOf("Java"));// 7

        // 判断  itcast 所在的位置
        System.out.println(str.indexOf("itcast"));// -1
    }
}

package com.bn.api_demo.string_demo;

/*
    已知字符串,完成右侧需求
    String str = "I Love Java, I Love Heima";
    需求:
    1.将所有 Love 替换为 Like ,打印替换后的新字符串
    2.截取字符串 "I Love Hei"
    3.截取字符串 "Java"

 */
public class Test2 {
    
    
    public static void main(String[] args) {
    
    
        String str = "I Love Java, I Love Hei";

        // 1.将所有 Love 替换为 Like ,打印替换后的新字符串
        System.out.println(str.replace("Love", "Like"));
        // 2.截取字符串 "I Love Heima"
        System.out.println(str.substring(13));
        // 3.截取字符串 "Java"
        System.out.println(str.substring(7 , 11));

    }
}

6 正则表达式

6.1 概述 :

  • 正则表达式通常用来校验,检查字符串是否符合规则的

6.2 体验正则表达式

package com.bn.regex_demo;

import java.util.Scanner;

/*
    设计程序让用户输入一个QQ号码,验证QQ号的合法性:
    1. QQ号码必须是5--15位长度
    2. 而且首位不能为0
    3. 而且必须全部是数字

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

        System.out.println("请输入您的qq号码:");
        String qq = sc.nextLine();

        System.out.println(checkQQ2(qq));

    }

    private static boolean checkQQ(String qq) {
    
    
//        1. QQ号码必须是5--15位长度
        if (qq.length() < 5 || qq.length() > 15) {
    
    
            return false;
        }
//       2 . 而且首位不能为0
        if (qq.charAt(0) == '0') {
    
    
            return false;
        }

//        2. 而且必须全部是数字
        for (int i = 0; i < qq.length(); i++) {
    
    
            char ch = qq.charAt(i);
            if (ch < '0' || ch > '9') {
    
    
                return false;
            }
        }

        return true;
    }

    // 正则表达式改进
    private static boolean checkQQ2(String qq) {
    
    
        return qq.matches("[1-9][0-9]{4,14}");
    }
}

6.3 正则表达式的语法

  • boolean matches(正则表达式) :如果匹配正则表达式就返回true,否则返回false
    • boolean matches(正则表达式) :如果匹配正则表达式就返回true,否则返回false
  • 字符类
    • [abc] :代表a或者b,或者c字符中的一个。
    • [^abc]:代表除a,b,c以外的任何字符。
    • [a-z] :代表a-z的所有小写字符中的一个。
    • [A-Z] :代表A-Z的所有大写字符中的一个。
    • [0-9] :代表0-9之间的某一个数字字符。
    • [a-zA-Z0-9]:代表a-z或者A-Z或者0-9之间的任意一个字符。
    • [a-dm-p]:a 到 d 或 m 到 p之间的任意一个字符
package com.bn.regex_demo;
/*
    字符类 : 方括号被用于指定字符
    [abc] :代表a或者b,或者c字符中的一个。
    [^abc]:代表除a,b,c以外的任何字符。
    [a-z] :代表a-z的所有小写字符中的一个。
    [A-Z] :代表A-Z的所有大写字符中的一个。
    [0-9] :代表0-9之间的某一个数字字符。
    [a-zA-Z0-9]:代表a-z或者A-Z或者0-9之间的任意一个字符。
    [a-dm-p]:a 到 d 或 m 到 p之间的任意一个字符

    需求 :
    1 验证str是否以h开头,以d结尾,中间是a,e,i,o,u中某个字符
    2 验证str是否以h开头,以d结尾,中间不是a,e,i,o,u中的某个字符
    3 验证str是否a-z的任何一个小写字符开头,后跟ad
    4 验证str是否以a-d或者m-p之间某个字符开头,后跟ad
    注意: boolean  matches(正则表达式) :如果匹配正则表达式就返回true,否则返回false
 */
public class RegexDemo {
    
    
    public static void main(String[] args) {
    
    
//        1 验证str是否以h开头,以d结尾,中间是a,e,i,o,u中某个字符
        System.out.println("had".matches("h[aeiou]d"));

//        2 验证str是否以h开头,以d结尾,中间不是a,e,i,o,u中的某个字符
        System.out.println("hwd".matches("h[^aeiou]d"));

//        3 验证str是否a-z的任何一个小写字符开头,后跟ad
        System.out.println("aad".matches("[a-z]ad"));

//        4 验证str是否以a-d或者m-p之间某个字符开头,后跟ad
        System.out.println("bad".matches("[a-dm-p]ad"));

    }
}
  • 逻辑运算符
    • && :并且
    • | :或者
package com.itheima.regex_demo;
/*
    逻辑运算符 :
        1 && : 并且
        2 |  : 或者

    需求 :
        1 要求字符串是除a、e、i、o、u外的其它小写字符开头,后跟ad
        2 要求字符串是aeiou中的某个字符开头,后跟ad
 */
public class RegexDemo2 {
    
    
    public static void main(String[] args) {
    
    
//        1 要求字符串是除a、e、i、o、u外的其它小写字符开头,后跟ad
        System.out.println("vad".matches("[a-z&&[^aeiou]]ad"));
//        2 要求字符串是aeiou中的某个字符开头,后跟ad
        System.out.println("aad".matches("[a|e|i|o|u]ad"));
    }
}

  • 预定义字符类
    • “.” : 匹配任何字符。
    • “\d”:任何数字[0-9]的简写;
    • “\D”:任何非数字[^0-9]的简写;
    • “\s” : 空白字符:[ \t\n\x0B\f\r] 的简写
    • “\S” : 非空白字符:[^\s] 的简写
    • “\w” :单词字符:[a-zA-Z_0-9]的简写
    • “\W”:非单词字符:[^\w]
package com.bn.regex_demo;
/*
    预定义字符 : 简化字符类的书写

    "."  :匹配任何字符。
    "\d" :任何数字[0-9]的简写
    "\D" :任何非数字[^0-9]的简写
    "\s" :空白字符:[\t\n\x0B\f\r] 的简写
    "\S" :非空白字符:[^\s] 的简写
    "\w" :单词字符:[a-zA-Z_0-9]的简写
    "\W" :非单词字符:[^\w]

    需求 :
       1 验证str是否3位数字
       2 验证手机号:1开头,第二位:3/5/8,剩下9位都是0-9的数字
       3 验证字符串是否以h开头,以d结尾,中间是任何字符

 */
public class RegexDemo3 {
    
    
    public static void main(String[] args) {
    
    
//        1 验证str是否3位数字
        System.out.println("123".matches("\\d\\d\\d"));

//        2 验证手机号:1开头,第二位:3/5/8,剩下9位都是0-9的数字 )
        System.out.println("15188888888".matches("1[358]\\d\\d\\d\\d\\d\\d\\d\\d\\d"));

//        3 验证字符串是否以h开头,以d结尾,中间是任何字符
        System.out.println("had".matches("h.d"));
    }
}

  • 数量词
    • X? : 0次或1次
    • X* : 0次到多次
    • X+ : 1次或多次
    • X{n} : 恰好n次
    • X{n,} : 至少n次
    • X{n,m}: n到m次(n和m都是包含的)
package com.bn.regex_demo;

/*
    数量词 :
        - X?    : 0次或1次
        - X*    : 0次到多次
        - X+    : 1次或多次
        - X{n}  : 恰好n次
        - X{n,} : 至少n次
        - X{n,m}: n到m次(n和m都是包含的)

    需求 :
      1 验证str是否3位数字
      2 验证str是否是多位(大于等于1次)数字
      3 验证str是否是手机号 ( 1开头,第二位:3/5/8,剩下9位都是0-9的数字)
      4 验证qq号码:1).5--15位;2).全部是数字;3).第一位不是0

 */
public class RegexDemo4 {
    
    
    public static void main(String[] args) {
    
    
//        1 验证str是否3位数字
        System.out.println("123".matches("\\d{3}"));

//        2 验证str是否是多位(大于等于1次)数字
        System.out.println("123456".matches("\\d+"));

//        3 验证str是否是手机号 ( 1开头,第二位:3/5/8,剩下9位都是0-9的数字)
        System.out.println("15188888888".matches("1[358]\\d{9}"));

//        4 验证qq号码:1).5--15位;2).全部是数字;3).第一位不是0
        System.out.println("122103987".matches("[1-9]\\d{4,14}"));
    }
}

  • 分组括号 :
    • 将要重复使用的正则用小括号括起来,当做一个小组看待
package com.bn.regex_demo;
/*
    分组括号 : 将要重复使用的正则用小括号括起来,当做一个小组看待
    需求 :  window秘钥 , 分为5组,每组之间使用 - 隔开 , 每组由5位A-Z或者0-9的字符组成 , 最后一组没有 -
    举例 :
        xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
        DG8FV-B9TKY-FRT9J-99899-XPQ4G
    分析:
        前四组其一  :DG8FV-    正则:[A-Z0-9]{5}-
        最后一组    :XPQ4G     正则:[A-Z0-9]{5}

    结果 : ([A-Z0-9]{5}-){4}[A-Z0-9]{5}

 */
public class RegexDemo5 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("DG8FV-B9TKY-FRT9J-99899-XPQ4G".matches("([A-Z0-9]{5}-){4}[A-Z0-9]{5}"));
    }
}

  • 字符串中常用含有正则表达式的方法
    • public String[] split ( String regex ) 可以将当前字符串中匹配regex正则表达式的符号作为"分隔符"来切割字符串。
    • public String replaceAll ( String regex , String newStr ) 可以将当前字符串中匹配regex正则表达式的字符串替换为newStr。
package com.bn.regex_demo;

import java.util.Arrays;

/*

    1 字符串中常用含有正则表达式的方法
        public String[] split ( String regex ) 可以将当前字符串中匹配regex正则表达式的符号作为"分隔符"来切割字符串。
        public String replaceAll ( String regex , String newStr ) 可以将当前字符串中匹配regex正则表达式的字符串替换为newStr。

    需求:
        1 将以下字符串按照数字进行切割
        String str1 = "aa123bb234cc909dd";

        2 将下面字符串中的"数字"替换为"*“a
        String str2 = "我卡里有100000元,我告诉你卡的密码是123456,要保密哦";

 */
public class RegexDemo6 {
    
    
    public static void main(String[] args) {
    
    
        // 1 将以下字符串按照数字进行切割
        String str1 =  "aa123bb234cc909dd";
        String[] strs = str1.split("\\d+");
        System.out.println(Arrays.toString(strs));

        // 2 将下面字符串中的"数字"替换为"*“a
        String str2 = "我卡里有100000元,我告诉你卡的密码是123456,要保密哦";
        System.out.println(str2.replaceAll("\\d+" , "*"));
    }
}

7 引用数据类型使用

7.1 使用方式

- 基本数据类型可以当做方法的参数,返回值及成员变量使用,传递或者保存的是数据值。
- 引用数据类型也可以当做方法的参数,返回值及字段使用,传递或者保存的是对象的引用(地址)。
- 特别要注意,如果是抽象类或者接口那么传递或者保存的就是子类对象的地址引用了
package com.bn.datatype_demo;


public interface Player {
    
    
    public abstract void play();
}

abstract class Mp3Player implements Player {
    
    

}

class IPod extends Mp3Player {
    
    
    @Override
    public void play() {
    
    
        System.out.println("IPod播放音乐...");
    }
}


package com.bn.datatype_demo;

/*
   1 分别定义含有Play,Mp3Player , Ipod参数的方法,并调用传入实参进行测试

   2  定义一个学生类,里面定义含有Player, Mp3Player,Ipod类型的成员变量
      创建学生对象并给成员变量赋值

 */
public class PlayerTest {
    
    
    public static void main(String[] args) {
    
    
        show1(new IPod());
        show2(new IPod());
        show2(new IPod());

        Student s = new Student();
        s.setPlayer(new IPod());
        s.setMp3Player(new IPod());
        s.setiPod(new IPod());
    }

    public static void show1(Player player) {
    
    // 方法的参数是一个接口 , 接收实现类对象
        player.play();
    }

    public static void show2(Mp3Player player) {
    
    // 方法的参数是一个抽象类 , 接收子类对象
        player.play();
    }

    public static void show3(Mp3Player player) {
    
    // 方法的参数是具体的类 , 接收此类对象或者子类对象
        player.play();
    }
}

/*
    定义一个学生类,里面定义含有Player, Mp3Player,Ipod类型的成员变量
    创建学生对象并给成员变量赋值
 */
class Student {
    
    
    private Player player;   // 接口的类型的成员变量 , 保存的是实现类对象地址
    private Mp3Player mp3Player; // 实现类的类型的成员变量 , 保存的是子类对象地址
    private IPod iPod; // 具体类类型的成员变量 , 保存的是此类对象或者此类的子类对象地址


    public Player getPlayer() {
    
    
        return player;
    }

    public void setPlayer(Player player) {
    
    
        this.player = player;
    }

    public Mp3Player getMp3Player() {
    
    
        return mp3Player;
    }

    public void setMp3Player(Mp3Player mp3Player) {
    
    
        this.mp3Player = mp3Player;
    }

    public IPod getiPod() {
    
    
        return iPod;
    }

    public void setiPod(IPod iPod) {
    
    
        this.iPod = iPod;
    }
}

8 Collection集合

8.1 集合和数组的区别

  • 长度区别
    • 数组 : 长度固定
    • 集合 : 长度可变
  • 存储数据类型
    • 数组 : 可以存储基本数据类型, 也可以存储引用数据类型
    • 集合 : 只能存储引用数据类型 , 要想存储基本数据类型 , 需要存储对应的包装类类型

8.2 集合的体系

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ivltlNy2-1683635543380)(.\img\image-20210404232635762.png)]

8.3 Collection集合常用的方法

  • 在学习集合体系,一般先学习顶层接口。学习了顶层接口的方法,子类型继承而来的方法,就可以不用重复学习。
    • public boolean add(E e): 把给定的对象添加到当前集合中 。
    • public void clear() :清空集合中所有的元素。
    • public boolean remove(E e): 把给定的对象在当前集合中删除。
    • public boolean contains(Object obj): 判断当前集合中是否包含给定的对象。
    • public boolean isEmpty(): 判断当前集合是否为空。
    • public int size(): 返回集合中元素的个数。
    • public Object[] toArray(): 把集合中的元素,存储到数组中

8.4 迭代器

  • 概述 :
    • 迭代器就是对Iterator的称呼 , 专门用来对Collection集合进行遍历使用的。学习迭代器的目的就是为了遍历集合
  • 注意 :
    • 只有继承/实现Iterable接口才具有迭代的能力
    • Collection接口继承了Iterable接口所以 , Collection及其子类都具备迭代的能力
  • 获取迭代器对象的方式
    • 通过Collection集合对象调用Iterable接口中的iterator方法 , 就可以获取迭代器对象
  • Iterator(迭代器)中的方法
    boolean hasNext() 如果迭代具有更多元素,则返回 true 。
    E next() 返回迭代中的下一个元素。
    default void remove() 从底层集合中删除此迭代器返回的最后一个元素(可选操作)。
  • 迭代器的注意事项
    • 当迭代器迭代元素完成后,不能继续next获取元素,否则会报:NoSuchElementException
    • 当迭代器在使用的过程中,不能使用集合对象直接增删元素。会导致报错ConcurrentModificationException。如果要删除可以使用迭代器来删除

8.5 增强for循环

  • 增强for循环(foreach),专门用来遍历集合或者数组,底层实现使用迭代器

  • 定义格式 :

    for(元素的类型 变量名 : 数组/单列集合 ){
          
          
        变量代表的就是集合或者数组的元素
    }
    

Guess you like

Origin blog.csdn.net/wanghaoyingand/article/details/130588238