Java第十二天~第十三天/11.04~11.05

来源:互联网 发布:七大查找算法 编辑:程序博客网 时间:2024/06/05 15:55

第十二天/11.04

一、选择排序

从0索引开始,用它对应的元素依次和后面索引对应的元素进行比较,小的往前放,第一次比较完毕后,最小值出现在最小索引处,依次比较,就可以得到一个排好序的数组。

package org.westos_01;/** * 选择排序: *      数组的0索引依次和后面的索引进行比较,对应的元素小的往前方法,依次比较,就可以得到一个排好序的数组 * @author 小鑫 */public class ArrayDemo {  public static void main(String[] args) {    //定义一个数组,静态初始化      int[] arr={24,21,13,3,8,1,41,23};      System.out.println("排序前");      printArray(arr);//  [24, 21, 13, 3, 8, 1, 41, 23]      selectSort(arr);      System.out.println("排序后");      printArray(arr); //[1, 3, 8, 13, 21, 23, 24, 41]}  //将选择排序的代码封装成一个独立的功能  public static void selectSort(int[] arr){      for(int i=0;i<arr.length-1;i++){          for(int j=i+1;j<arr.length;j++){              if(arr[i]>arr[j]){              int temp=arr[i];              arr[i]=arr[j];              arr[j]=temp;              }          }      }  }  //遍历数组  public static void printArray(int[] 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]+", ");          }      }  }}

这里写图片描述

二、二分查找

二分查找的前提:必须是一个排好序的数组,否则谈不上二分查找
思想:猜想中间索引,将数组减半
步骤:
1)有一个排好序的数组
2)定义最小索引和最大索引
3)计算中间索引
4)用中间索引对应元素和要查找的元素进行比较
相等:直接返回中间索引
不相等:大了,左边找;小了,右边找
5)重新获取最小索引和最大索引
6)重复步骤3)、步骤4)、步骤5),找到为止!

package org.westos_Array;/** * 使用二分查找,找到指定元素的索引 * @author 小鑫 */public class ArrayDemo2 {   public static void main(String[] args) {    int[] arr={11,22,33,44,55,66,77};    int index = getIndex(arr, 44);    System.out.println(index); //3    int index2 = getIndex(arr, 333);    System.out.println(index2); //-1}   /**    *     * @param arr    * @param value    * @return    */   public static int getIndex(int[] arr,int value){       int min=0;       int max=arr.length-1;       //中间索引       int mid=(min+max)/2;       while(arr[mid]!=value){           if(arr[mid]>value){               //重新获取最大索引               max=mid-1;           }else if(arr[mid]<value){               //重新获取最小索引               min=mid+1;           }           //如果找不到,返回-1           if(min>max){               return -1;           }           mid=(min+max)/2;       }       return mid;   }}

注意:如果数组没有排好序,使用二分查找查找某一元素的索引时,由于进行排序从而打乱了原来数组中的元素位置,所以找出来该元素的索引有可能是错误的!
这里写图片描述

三、Arrays类

1、Arrays:此类包含用来操作数组(比如排序和搜索)的各种方法(针对数组操作的工具类)
*
* 常用的几个方法:
* public static String toString(int[] a):将任意类型的数组以字符串形式显示出来!
* public static void sort(int[] a):快速排序:(将给定数组中元素升序排序)
* public static int binarySearch(int[] a, int key):当前int数组一定是有序数组
* 使用二分搜索法来搜索指定的 int 型数组,以获得指定的值

package org.westos_Array_02;import java.util.Arrays;/** * Arrays:此类包含用来操作数组(比如排序和搜索)的各种方法(针对数组操作的工具类) *   *  常用的几个方法: *          public static String toString(int[] a):将任意类型的数组以字符串形式显示出来! *          public static void sort(int[] a):快速排序:(将给定数组中元素升序排序) *          public static int binarySearch(int[] a, int key):当前int数组一定是有序数组 *              使用二分搜索法来搜索指定的 int 型数组,以获得指定的值 * @author 小鑫 */public class ArrayDemo {   public static void main(String[] args) {    int[] arr={24,16,82,57,13};    //将数组转换成字符串形式    System.out.println(Arrays.toString(arr));    //快速排序    Arrays.sort(arr);    //将排好序的数组以String形式显示出来    System.out.println(Arrays.toString(arr));    //查找元素    int index = Arrays.binarySearch(arr, 57);    System.out.println(index);    int index2 = Arrays.binarySearch(arr, 500);    System.out.println(index2);   }}

这里写图片描述
2、练习

package org.westos_Array_02;import java.util.Scanner;/** * 字符串中的字符进行排序。        举例:"dacgebf"        结果:"abcde    改进:键盘录入一个字符串 * @author 小鑫 * */public class ArrayTest {   public static void main(String[] args) {       //创建键盘录入对象       Scanner sc=new Scanner(System.in);       //录入接受数据       System.out.println("请输入一个字符串");       String line=sc.nextLine();       //将字符串转换成字符数组       char[] chs = line.toCharArray();       //给字符数组进行冒泡排序       bubbleSort(chs);       //最终要的是字符串,所以还需要将字符数组转换成字符串       String result = String.valueOf(chs);       System.out.println(result);}   public static void bubbleSort(char[] chs){       for(int i=0;i<chs.length-1;i++){           for(int j=0;j<chs.length-1-i;j++){               if(chs[j]>chs[j+1]){                   char temp=chs[j];                   chs[j]=chs[j+1];                   chs[j+1]=temp;               }           }       }   }}

这里写图片描述

四、System类

1、System:该类没有构造方法,所以字段和成员方法都用静态修饰
常用的成员方法:
public static void gc()运行垃圾回收器。
public static void exit(int status)终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。
public static long currentTimeMillis():返回当前的时间毫秒值
public static void arraycopy(Object src,int srcPos,Object dest, int destPos,int length)指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束

package org.westos_sysem_01;/** * System:该类没有构造方法,所以字段和成员方法都用静态修饰 *  *              常用的两个字段: *                      in ,out都和流有关系:java.io... *  *                  PrintStream(字节打印流) ps = System.out ;        标准输出流 *                  PrintWriter(字符打印流) *  *                  InputStream   in =  System.in;      标准输入流        *  *          常用的成员方法: *              public static void gc()运行垃圾回收器。                     调用 gc 方法暗示着 Java 虚拟机做了一些努力来回收未用对象,以便能够快速地重用这些对象当前占用的内存,最终调用的就是重写之后finalize()回收不用                    的对象! * @author 小鑫 * */public class SystemDemo {  public static void main(String[] args) {    Person p=new Person("Sunshine",20);    System.out.println(p);//Person [name=Sunshine, age=20]    p=null;//当前Person变成空了,没有更多引用    //启动垃圾回收器--->调用gc()方法暗示着让Java虚拟机回收不用的对象    System.gc();//当前垃圾回收器需要回收不用的对象Person [name=Sunshine, age=20]}}public class Person {  private String name;  private int age;    public Person() {        super();        // TODO Auto-generated constructor stub    }    public Person(String name, int age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "Person [name=" + name + ", age=" + age + "]";    }   //重写Object中的finalize()方法    @Override        protected void finalize() throws Throwable {            System.out.println("当前垃圾回收器需要回收不用的对象"+this);            super.finalize();        }}

2、exit()方法和currentTimeMillis()方法

package org.westos_sysem_02;/** *  public static void exit(int status)终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。    public static long currentTimeMillis():返回当前的时间毫秒值 * @author 小鑫 * */public class SystemDemo {public static void main(String[] args) {    //输出语句     /* System.out.println("helloworld");      //调用exit()方法      //System.exit(0);//JVM已经退出,还可以结束循环语句      System.out.println("helloJavaSE");//不打印,此时JVM已经退出了      */    //计算某一个应用程序耗时的毫秒值      long start=System.currentTimeMillis();      for(int i=0;i<10000;i++){          System.out.println(i);      }      long end=System.currentTimeMillis();      System.out.println("当前for循环耗时:"+(end-start)+"毫秒");//当前for循环耗时:106毫秒}}

3、arraycopy()方法

package org.westos_sysem_02;import java.util.Arrays;/** * public static void arraycopy(Object src,int srcPos,Object dest, int destPos,int length) *  指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束 * @author 小鑫 * */public class SystemDemo2 {  public static void main(String[] args) {    int[] arr1={11,22,33,44,55,66};    int[] arr2={4,5,6,7,8};    //复制数组    System.arraycopy(arr1, 2, arr2, 3, 1);    System.out.println("arr1"+Arrays.toString(arr1));    System.out.println("arr2"+Arrays.toString(arr2));}}

这里写图片描述

五、BigDecimal类

1、作用
对于浮点类型的数据类说,他们存储和整数的存储是不一致的,是按照有效数字位来进行存储的,浮点类型的数据计算的时候
* 容易损失精度,计算出来的结果不精确,Java针对这种情况:提供了这个BigDecimal:
作用:来提供浮点类型数据的精确计算!可变的、任意精度的有符号十进制数
* 构造方式:
* public BigDecimal(String val)

2、加减乘除方法

package org.westos_bigdecimal;import java.math.BigDecimal;/** * public BigDecimal(String val) *      常用的成员方法; *          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:舍入的一种模式:ROUND_HALF_UP * @author 小鑫 * */public class BigDecimalDemo2 {   public static void main(String[] args) {    BigDecimal bd1=new BigDecimal("0.01");    BigDecimal bd2=new BigDecimal("0.09");    //public BigDecimal add(BigDecimal augend):加        System.out.println("add:"+bd1.add(bd2));//add:0.10    //public BigDecimal subtract(BigDeciaml subtrahend):减        System.out.println("subtract:"+bd2.subtract(bd1));//subtract:0.08    //public BigDecimal multiply(BigDecimal multiplicand):乘法        BigDecimal bd5 = new BigDecimal("1.501") ;        BigDecimal bd6 = new BigDecimal("100.0") ;        System.out.println("mul:"+bd5.multiply(bd6));//mul:150.1000    //public BigDecimal divide(BigDecimal divisor):除        BigDecimal bd7 = new BigDecimal("1.301") ;        BigDecimal bd8 = new BigDecimal("100") ;        System.out.println("div:"+bd7.divide(bd8));//div:0.01301    //public BigDeciaml divide(BigDeciaml divisor,int scale,int roundingMode);    //参数1:商,    参数2:保留几位小数,参数3:舍入的一种模式:ROUND_HALF_UP        System.out.println("div:"+bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));//div:0.013        System.out.println("div:"+bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));//div:0.01301000}}

六、BigInteger类

1、作用: BigInteger:用来计算超出了Integer类型范围的数据

package org.westos_biginteger;import java.math.BigInteger;/** *  BigInteger:用来计算超出了Integer类型范围的数据 * @author 小鑫 * */public class BigIntegerDemo {  public static void main(String[] args){      //查看Integer类的最大值     System.out.println(Integer.MAX_VALUE);//2147483647     //创建Integer对象     //Integer i=new Integer("2147483649");     //System.out.println(i);//java.lang.NumberFormatException: For input string: "2147483649"     //当前该数据超出Integer的取值范围     BigInteger i=new BigInteger("2147483649");     System.out.println(i);//2147483649  }}

2、加减乘除方法

package org.westos_biginteger;import java.math.BigInteger;/** * BigInteger的构造方法 *      public BigInteger(String val)将字符串表示的数字封装成BigInteger类型 *  成员方法: *          public BigInteger add(BigInteger val) *          public BigInteger subtract(BigInteger val) *          public BigInteger multiply(BigInteger val) *          public BigInteger divide(BigInteger val) *          public BigInteger[] divideAndRemainder(BigInteger val)   *          返回一个BigInteger数组,数组中的元素:商,余数 * @author 小鑫 */public class BigIntegerDemo2 {  public static void main(String[] args) {      //创建BigInteger对象      BigInteger bg1=new BigInteger("100");      BigInteger bg2=new BigInteger("20");      //public BigInteger add(BigInteger val)加      System.out.println("add:"+bg1.add(bg2));//add:120      //public BigInteger subtract(BigInteger val)减      System.out.println("sub:"+bg1.subtract(bg2));//sub:80      //public BigInteger multiply(BigInteger val)乘      System.out.println("mul:"+bg1.multiply(bg2));//mul:2000      //public BigInteger divide(BigInteger val)除      System.out.println("div:"+bg1.divide(bg2));//div:5      //public BigInteger[] divideAndRemainder(BigInteger val)      //返回一个BigInteger数组,数组中的元素:商,余数      BigInteger[] result = bg1.divideAndRemainder(bg2);      System.out.println("商是result[0]为:"+result[0]+" 余数是result[1]为:"+result[1]);//商是result[0]为:5 余数是result[1]为:0}}

七、Calendar类

1、日历类,是一个抽象类,不能实例化

 package org.westos_calendar;import java.util.Calendar;/** * Calendar:日历类: *      Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法, *                  并为操作日历字段(例如获得下星期的日期)提供了一些方法 *      Calendar该类是一个抽象类:不能实例化的,所以通过一下这个方法来创建对象 *                          public static Calendar getInstance() *                          public int get(int field)返回给定日历字段的值 *       *      public static final int YEAR:表示日历中 的年 *      public static final int MONTH:月份:是0开始计算的 *      public static final int DATE:和DAY_OF_MONTH是同义词,表示月份中的某天 * @author 小鑫 * */public class CalendarDemo {    public static void main(String[] args) {        //创建日历对象        Calendar calendar=Calendar.getInstance();        //获取年        //public static final int YEAR:表示日历中 的年        int year = calendar.get(Calendar.YEAR);        //获取年中的月份        //public static final int MONTH        int month = calendar.get(Calendar.MONTH);        //获取月中的天        //public static final int DATE        int date = calendar.get(Calendar.DATE);        System.out.println(year+"-"+(month+1)+"-"+date);//2017-11-6    }}

2、为给定的日历的字段添加或者减去时间偏移量

package org.westos_calendar;import java.util.Calendar;/** * Calendar常用的成员方法: *          public abstract void add(int field,int amount) *              为给定的日历的字段添加或者减去时间偏移量 *          public final void set(int year,int month,int date) *                  设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值 * @author 小鑫 * */public class CalendarDemo2 {   public static void main(String[] args) {      //创建日历类对象      Calendar c=Calendar.getInstance();      int year=c.get(Calendar.YEAR);      int month=c.get(Calendar.MONTH);      int date=c.get(Calendar.DATE);      System.out.println(year+"年"+(month+1)+"月"+date+"日");      //需求:三年前的今天      c.add(Calendar.YEAR, -3);      //重新获取年月日       year=c.get(Calendar.YEAR);       month=c.get(Calendar.MONTH);       date=c.get(Calendar.DATE);       System.out.println(year+"年"+(month+1)+"月"+date+"日");//2014年11月6日       //5年后的十天前       c.add(Calendar.YEAR,5);       c.add(Calendar.DATE,-10);       //重新获取年月日       year=c.get(Calendar.YEAR);       month=c.get(Calendar.MONTH);       date=c.get(Calendar.DATE);       System.out.println(year+"年"+(month+1)+"月"+date+"日");//2019年10月27日       //public final void set(int year,int month,int date)       //获取某年某月某日,注意月份+1       c.set(2018, 10, 1);       //获取年月日       year=c.get(Calendar.YEAR);       month=c.get(Calendar.MONTH);       date=c.get(Calendar.DATE);       System.out.println(year+"年"+(month+1)+"月"+date+"日");//2018年11月1日}}

3、键盘录入一个年份,获取任意一年的二月有多少天

package org.westos_calendar;import java.util.Calendar;import java.util.Scanner;/** * 键盘录入一个年份,获取任意一年的二月有多少天 * 分析: *    1)键盘录入 *    2)获取日历类对象,getInstance() *    3)设置一个日历字段 *      日历类对象.set(year,2,1):其实表示3月1日 *    4)将时间往前推一天 *      日历类对象.add(Calendar.DATE,-1) *    5)获取DATE月份中的天 * @author 小鑫 * */public class CalendarTest {   public static void main(String[] args) {       //创建键盘录入       Scanner sc=new Scanner(System.in);       //录入并接收       System.out.println("请您输入一个年份");       int year=sc.nextInt();       //创建日历类对象       Calendar c=Calendar.getInstance();       c.set(year, 2, 1);//month+1 实则为3月1日       //将时间往前推一天       c.add(Calendar.DATE, -1);       System.out.println("这一年的二月有"+c.get(Calendar.DATE));}}

这里写图片描述

八、Date类

1、Date类常用的构造方法

package org.westos_date_01;import java.util.Date;/** * Date类:日期类 *     表示特定时间,精确到毫秒 *      *      常用构造方法: *          public Date():表示分配的一个Date对象:无参: 通过无参构造获取当前系统的具体的时间 *          public Date(long date):指定一个时间毫秒值  和它1970-1-1 00:00:00有时间差 * @author 小鑫 * */public class DateDemo {   public static void main(String[] args) {      //创建日期对象       Date d=new Date();       //输出日期对象       System.out.println(d);//Wed Nov 08 17:54:52 CST 2017       //设置一个时间long       long time=1000/60/60;       Date d2=new Date(time);       System.out.println(d2);//Thu Jan 01 08:00:00 CST 1970   }}

2、Date中的成员方法

package org.westos_date_01;import java.util.Date;/** * Date中的成员方法 *       public long getTime():获取当前时间毫秒值 *       如果知道Date对象,可以通过getTime()获取时间毫秒值 *       public void setTime(long time) * @author 小鑫 * */public class DateDemo2 {   public static void main(String[] args) {     //创建一个日期对象      Date d=new Date();      System.out.println(d);//Wed Nov 08 18:04:54 CST 2017      //public long getTime():获取当前时间毫秒值      long time =d.getTime();      System.out.println(time);//1510135494954      System.out.println(System.currentTimeMillis());//1510135494954      //public void setTime(long time)      d.setTime(1000);      System.out.println(d);//Thu Jan 01 08:00:01 CST 1970}}

3、Date类格式与String类文本格式想互转化

package org.westos_date_01;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * 将Date类对象--->String类型的文本格式日期:格式化 *    public final String format(Date date) * String类日期的文本格式--->Date日期对象:解析 *    public Date parse(Sring source)该方法会抛出异常:ParseException(解析异常:编译时期异常) *    要进行转换:必须使用中间桥梁:DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。 *  日期/时间格式化子类(如 SimpleDateFormat)允许进行格式化(也就是日期Date -> 文本String)、解析(文本String-> 日期Date)和标准化 *  *      但是,DateFormat是抽象类,不能直接实例化,使用的是它更具体的子类进行实例化: *      SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类 *  *      常用的构造方法: *              Date---格式化--->String文本格式 *               *              public SimpleDateFormat(String pattern)用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat *  *      日期和时间模式 *          y           年   比如:2017---->yyyy *          M           年中的月份:2------>MM *          d           月份中的天数 :----->dd *          H           小时              HH *          m           小时中的分钟数     mm *          s           分钟中的秒数      ss *  * @author 小鑫 * */public class DateFormatDemo {   public static void main(String[] args) throws ParseException {     //创建日期对象     Date d=new Date();     //创建SimpleDateFormat类对象,用该对象格式化Date对象     SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     String dateStr=sdf.format(d);     System.out.println(dateStr);//2017-11-08 18:39:06     System.out.println("----------------");     //String日期"文本格式"--->解析--->Date对象     /**      * 注意事项:      *   一定要保证SimpleDateFormat中的String Pattern这个模式和当前给的字符串的文本格式的模式必须一致!      */     String s="2017-11-08 19:20:36";     //创建SimpleDateFormat类的对象,用该对象解析String的日期文本格式     SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//形式必须与String类型一样     //解析     //public Date parse(Sring source)     Date d2 = sdf2.parse(s);     System.out.println(d2);//Wed Nov 08 19:20:36 CST 2017}}

4、Date类和String类的工具类

package org.westos_date_02;import java.text.ParseException;import java.util.Date;/** * 日期和String相互转换的一个测试类 * @author 小鑫 * */public class DateUtilDemo {   public static void main(String[] args) throws ParseException {      //Date--->String      Date d=new Date();      String str=DateUtil.dateToString(d, "yyyy-MM-dd HH:mm:ss");      System.out.println(str);//2017-11-08 19:10:36      //String--->Date      String s="2017-11-11 11:11:11";      Date date=DateUtil.stringToDate(s, "yyyy-MM-dd HH:mm:ss");      System.out.println(date);//Sat Nov 11 11:11:11 CST 2017}}import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * 这是将Date和String相互转换的日期工具类 * @author 小鑫 * */public class DateUtil {    //将无参构造私有化,为了不让外界创建对象    private DateUtil(){   }    /**     * 该方法是将Date日期对象格式化成一个String日期"文本格式"     * @param d     *    需要被转换的日期对象     * @param format     *    需要转换的时候提供的一种模式     * @return     *    最终返回的就是日期的文本格式     */    public static String dateToString(Date d,String format){        //创建SimpleDateFormat对象        SimpleDateFormat sdf=new SimpleDateFormat(format);        String str=sdf.format(d);        return str;        //链式编程        //return new SimpleDateFormat(format).format(d);    }    /**     *      * @param s     *    表示需要被解析的日期文本格式      * @param format     *    表示解析日期文本格式是需要使用的一种模式     * @return     *    返回日期Date对象     * @throws ParseException      */    public static Date stringToDate(String s,String format) throws ParseException{        //创建SimpleDateFormat对象        SimpleDateFormat sdf2=new SimpleDateFormat(format);        Date date = sdf2.parse(s);        return date;        //链式编程        //return new SimpleDateFormat(format).parse(s);    }}

5、练习:出生多少天?

package org.westos_date_02;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;/** * 键盘录入你的出生年月日,计算你来到这个世界有多少天了? * 分析: *   1)键盘录入生日,录入String类型数据 *   2)创建SimpleDateFormat对象指定模式 *   3)将String日期文本格式转换成Date对象 *   4)通过Date对象获取getTime():获取时间毫秒值 *   5)得到当前系统时间毫秒值(System.currentTimeMillis()) *   6)5)-4)=long类型时间值 *   7)换算成天数 * @author 小鑫 * */public class BirthTest {   public static void main(String[] args) throws ParseException {       //键盘录入并接收       Scanner sc=new Scanner(System.in);       //录入并接收       System.out.println("请输入您的生日");       String line = sc.nextLine();       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");       Date date = sdf.parse(line);       /*        *  //使用刚才DateUtil工具类        *  Date date=DateUtil.stringToDate(line, "yyyy-MM-dd");        */       //获取出生时的时间毫秒值       long oldTime = date.getTime();       //获取当前系统毫秒值       long nowTime = System.currentTimeMillis();       long time=nowTime-oldTime;       //换算       long day=time/1000/60/60/24;       System.out.println("你来到这个世界有"+day+"天了");   }}

这里写图片描述

九、Math类

常用的成员方法

package org.westos_math;/** * Math类提供了一些数学运行的方法 *      常用的成员方法: *              public static int abs(int a):绝对值 *              public static double ceil(double a):向上取整 *              public static double floor(double a):向下取整    *              public static double max(double a,double b):获取最大值 *              public static double min(double a,double 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):一个数的正平方跟 * @author 小鑫 * *///import static java.lang.Math.abs;//静态导入()import static(该方法一定是静态方法)public class MathDemo {  public static void main(String[] args) {        //public static int abs(int a):绝对值        System.out.println(java.lang.Math.abs(-100));//100        System.out.println(Math.abs(-100));//100        //public static double ceil(double a):向上取整        System.out.println("ceil:"+Math.ceil(12.34));//ceil:13.0        System.out.println("ceil:"+Math.ceil(12.54));//ceil:13.0        //public static double floor(double a):向下取整         System.out.println("floor:"+Math.floor(12.34));//floor:12.0        System.out.println("floor:"+Math.floor(12.56));//floor:12.0        //public static double max(double a,double b):获取最大值        System.out.println("max:"+Math.max(Math.max(10,20),30));//max:30        //public static double pow(double a,double b):a的b次幂        System.out.println("pow:"+Math.pow(2, 3));//pow:8.0        //public static long round(double a):四舍五入        System.out.println("round:"+Math.round(12.56));//round:13        //public static double sqrt(double a):一个数的正平方跟        System.out.println("sqrt:"+Math.sqrt(4));//sqrt:2.0}}

第十三天/11.05

一、正则表达式

1、正则表达式常用的语法:

正则表达式常用的语法:A:字符    x       字符 x :任意的字符    \\      反斜线字符在代码中书写正则表达式:\------>用两个\\代表一个反斜线    \t      制表符 ('\u0009')    \n      新行(换行)符 ('\u000A')  IO流中要写入换行符号:windows "\r\n"    \r      回车符 ('\u000D') B:字符类    [abc]       a、b 或 c(简单类)     [^abc]      任何字符,除了 a、b 或 c(否定)     [a-zA-Z]    a 到 z 或 A 到 Z,两头的字母包括在内(范围) :当前字母大小均可C:预定义字符类    .     任何字符    邮箱里面:如果本身就是.,那么在写正在表达式的时候,\.将当前.转义    \d          数字:[0-9]    \d在正则表达式应用的时候:[0-9]--->\\d    \w          单词字符:[a-zA-Z_0-9]:简单一些字符串,单词字符(规则:数字或者字母)                    javascript:[a-zA-Z0-9]D:边界匹配器    ^           行的开头     $          行的结尾    \b          单词边界 :                hello;world:haha:xixiE:Greedy 数量词    X?          X,一次或一次也没有     X*          X,零次或多次    X+          X,一次或多次     X{n}        X,恰好 n 次     X{n,}       X,至少 n 次    X{n,m}      X,至少 n 次,但是不超过 m 次 

2、普通方法校验QQ

package org.westos.regex_01;import java.util.Scanner;/** * 需求:校验一个QQ号码 *      定义一个规则:1)由5到10为组成的数字 *                2)不能以0开头   *  分析: *      1)键盘录入一个QQ号码,使用字符串接收 *      2)定义一个校验QQ的功能 *      3)在main()中调用返回boolean类型 * @author 小鑫 * */public class RegexDemo {  public static void main(String[] args) {     Scanner sc=new Scanner(System.in);     System.out.println("请输入一个QQ号");     String QQ = sc.nextLine();     //校验QQ的功能     boolean flag=checkQQ(QQ);     System.out.println(flag);  }     public static boolean checkQQ(String qq){         boolean flag=true;         if(qq.length()>=5 && qq.length()<=10){             if(!qq.startsWith("0")){                 //符合这个规则                 char[] chs = qq.toCharArray();                 //遍历字符数组                 for(int i=0;i<chs.length;i++){                     char ch=chs[i];                     if(!Character.isDigit(ch)){                        flag=false;                        break;                     }                 }             }else{                 flag=false;             }         }else{             flag=false;         }       return flag;     }}

3、正则表达式校验QQ

package org.westos.regex_01;import java.util.Scanner;/** * 需求:校验一个QQ号码 *      定义一个规则:1)由5到10为组成的数字 *                2)不能以0开头   *  分析: *      1)键盘录入一个QQ号码,使用字符串接收 *      2)定义一个校验QQ的功能 *      3)在main()中调用返回boolean类型 * @author 小鑫 * */public class RegexDemo2 {  public static void main(String[] args) {      Scanner sc=new Scanner(System.in);      System.out.println("请输入一个QQ号");      String line = sc.nextLine();      boolean flag = checkQQ(line);      System.out.println(flag); }  public static boolean checkQQ(String qq){      //定义正则规则      String regex="[1-9][0-9]{4,9}";      //public boolean matches(String regex)告知此字符串是否匹配给定的正则表达式。       boolean flag = qq.matches(regex);      return flag;      //或者可以直接返回      //return qq.matches("[1-9][0-9]{4,9}");  }}

4、正则表达式校验手机号码

package org.westos.regex_01;import java.util.Scanner;/** * 使用正则表达式校验手机号码: *      规则: *          手机号码: *              13689257284 *              13688886666 *              13892866555 *              18992844422 *              13257222222 *              ... *  *1)创建键盘录入对象,录入手机号码 *2)定义正则规则: *3)String类的特有功能 *          public boolean matches(String regex)告知此字符串是否匹配给定的正则表达式。  *4)输出 * @author 小鑫 * */public class RegesDemo3 {    public static void main(String[] args) {        Scanner sc=new Scanner(System.in);        System.out.println("请输入要校验的手机号码");        String phoneNumber = sc.nextLine();        //定义正则规则        String regex="1[38][0-9]{9}";        boolean flag = phoneNumber.matches(regex);        System.out.println(flag);    }}

这里写图片描述
5、正则表达式校验邮箱

package org.westos.regex_01;import java.util.Scanner;/** * 需求:校验邮箱: *      QQ邮箱: *          919081924@qq.com *          fengqingyang@163.com *          xxxxx@126.com *          zhangsan@westos.com *          lisi@sina.com *          wangwu@istone.com.cn.... * 分析:1)键盘录入邮箱 *      2)定义正则规则 *      3)使用String中的特有功能校验 *      4)输出即可 * @author 小鑫 * */public class RegexDemo4 {   public static void main(String[] args) {    Scanner sc=new Scanner(System.in);    System.out.println("请输入一个邮箱");    String email = sc.nextLine();    //定义正则规则    String regex="[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\.[a-zA-Z]{2,3})+";    /**     * \w--->[a-zA-Z_0-9]     * .--->\.     * \--->\\     */    //String regex2="\\w+@\\w{2,6}(\\.[a-zA-Z]{2,3})+";    //校验    boolean flag = email.matches(regex);    System.out.println(flag);   }}

二、分割功能

1、String的分割功能
public String[] split(String regex)根据给定正则表达式的匹配拆分此字符串

package org.westos.regex_split;import java.util.Scanner;/** * String的分割功能: *       * public String[] split(String regex)根据给定正则表达式的匹配拆分此字符串 *      返回值类型是一个字符串数组类型 *  * 应用场景: *      在一个给定范围内寻找需求   *      例如:String ages = "18-24" ; * @author 小鑫 * */public class RegexSplitDemo1 {   public static void main(String[] args) {       Scanner sc=new Scanner(System.in);       System.out.println("请输入一个年龄");       int age = sc.nextInt();//输入23       //定义一个字符串       String ages="18-25";       //定义正则规则       String regex="-";       //public String[] split(String regex)       String[] strArray = ages.split(regex);       //将当前字符数组转换成成int类型数据       int startAge = Integer.parseInt(strArray[0]);       int endAge = Integer.parseInt(strArray[1]);       if(age>=startAge && age<=endAge){           System.out.println("这是我想要找的");//这是我想要找的       }else{           System.out.println("这不是我想找的");       }   }}

2、分割功能的应用

package org.westos.regex_split;/** * 分割功能的应用 * @author 小鑫 * */public class RegexSplitDemo2 {  public static void main(String[] args) {      String str1="aa,bb,cc";      String[] strArray1 = str1.split(",");      for(int i=0;i<strArray1.length;i++){          System.out.println(strArray1[i]);      }      System.out.println("------------");      String str2="aa  bb      cc";      String[] strArray2 = str2.split(" +");      for(int i=0;i<strArray2.length;i++){          System.out.println(strArray2[i]);      }      System.out.println("------------");      String str3="aa.bb.cc";      String[] strArray3 = str3.split("\\.");      for(int i=0;i<strArray3.length;i++){          System.out.println(strArray3[i]);      }      System.out.println("------------");      //硬盘上的路径表现形式:用两个反斜线代表一个反斜线      //E:\\JavaSE\\JavaCode\\day13      String str4="E:\\JavaCode\\day13";      String[] strArray4 = str4.split("\\\\");      for(int i=0;i<strArray4.length;i++){          System.out.println(strArray4[i]);      }}}

这里写图片描述
3、String类中的替换功能

package org.westos.regex_split;/** * String类中的替换功能:和正则表达式有关系 *      public String replaceAll(String regex,String replacement) *              使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 * @author 小鑫 * */public class RegexSplitDemo3 {   public static void main(String[] args) {       //定义一个字符串       String str="helloworld12345JavaSE23586Javaweb";       //需求:让当前这个字符串中的数字不显示出来       //定义当前大串数字正则规则       String regex="\\d+";       String s="*";       //public String replaceAll(String regex,String replacement)       String result = str.replaceAll(regex, s);       System.out.println(result);//helloworld*JavaSE*Javaweb   }}

4、关于模式和匹配器的使用

package org.westos.regex_split;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * 关于模式和匹配器的使用:获取功能 *      模式和匹配器基本使用顺序 * @author 小鑫 * */public class RegexSplitDemo4 {   public static void main(String[] args) {       //public static Pattern compile(String regex)将给定的正则表达式编译成一个模式对象       //1)获取模式对象(通过正则规则)       Pattern p = Pattern.compile("a*b");       //2)通过模式获取匹配器对象,(将一个字符串类型的数据)       Matcher m = p.matcher("aaaab");       //3)调用Match(匹配器类)中的:public boolean matches():判断当前用户录入的字符串是否和当前的正则规则匹配       boolean flag = m.matches();       System.out.println(flag);//true       //上述方法过于麻烦,可以使用String类的功能       //定义正则规则       String regex="a*b";       String str="aaaab";       //public boolean matchers(String regex)       boolean flag2 = str.matches(regex);       System.out.println(flag2);//true}}

5、练习

package org.westos.regex_split;import java.util.Arrays;/** * 有如下一个字符串:"41 28 13 24 3 8 1"    请写代码实现最终输出结果是:"1 3 8 13 24 28 41"    分析:       1)定义字符串       2)使用分割功能成一个数组       3)动态初始化int数组 int[] arr=new int[字符串数组.length]       4)遍历int 数组       5)排序       6)遍历,用字符串缓冲区拼接 * @author 小鑫 * */public class RegexTest {    public static void main(String[] args) {        String str="41 28 13 24 3 8 1";        String[] strArray = str.split(" ");        int[] arr=new int[strArray.length];        for(int i=0;i<arr.length;i++){            //字符串转成int类型            arr[i]= Integer.parseInt(strArray[i]);                  }        //Array数组工具类排序        Arrays.sort(arr);        StringBuilder sb=new StringBuilder();        for(int i=0;i<arr.length;i++){            sb.append(arr[i]).append(" ");        }        String result = sb.toString().trim();        System.out.println(result);//1 3 8 13 24 28 41    }}

三、集合—Collection

1、集合的由来
集合的由来:
java语言是一种面向对象语言,面向对象语言对事物的描述是通过对象体现出来的,那么存储很多个学生,就需要使用容器变量进行存储
目前:学习过哪些容器变量呢?
* 数组,StringBuffer/StringBuilder,对于数组来说,数组的长度是固定的,不符合实际需求(长度不可变);对于StringBuffer来说始终在内存中返回
* 的是字符串类型,也不满足元素类型变化的要求;所以,Java就提供了一个技术:集合!
2、数组、String类以及集合的区别
面试题1:
* 集合和数组的区别?
* 1)长度的区别:
* 数组:长度是固定的;
* 集合:长度是可变的
* 2)存储数据类型的区别:
* 数组:可以存储引用类型,可以存储基本数据类型
* 集合:只能存储引用类型
* 3)存储元素的区别
* 数组:在同一个数组中,只能存储同一种数据类型的元素;举例 数组:杯子:只能装水
* 集合:可以 存储多种数据类型的元素; 举例:集合:杯子:装水,其他饮料…
面试题2:
* 数组中有没有length(),String类中有没有length(),集合中有没有length()?
* 数组:length属性
* String:length()
* 集合中:size()
3、集合的一些功能

package org.westos.collection;import java.util.ArrayList;import java.util.Collection;/** * 集合是可以存储多种类型的元素,但是,需求如果变化,针对集合来说,Java提供了很多集合类,每一种集合类的数据结构不一样,所以,将他们之间的共性内容抽取出来,就行了 * 一个集合的继承体系图! *  * 数据结构:存储数据的方式 *  * Collection: 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。 * 一些 collection 是有序的,而另一些则是无序的。JDK 不提供此接口的任何直接 实现:它提供更具体的子接口(如 Set 和 List)实现 *  * Collection的一些功能 * 添加功能: *      boolean add(Object e):给集合中添加指定的元素 *      boolean addAll(Collection c):添加一个集合中的所有元素 * 删除功能: *      void clear():删除一个集合中的所有元素,暴力删除,(不建议使用) *      boolean remove(Object o):删除一个集合中的指定元素 *      boolean removeAll(Collection c):删除一个集合中的所有元素?思考:删除所有算是删除还是删除一个算是删除? * 判断功能: *      boolean contains(Object o):判断一个集合中是否包含指定的单个元素 *      boolean containsAll(Collection c):判断一个集合中是否另一个集合;思考:是包含一个元素算是包含还是包含所有. *      boolean isEmpty():判断集合是否为空,如果为空,则返回true *       * 交集功能: *      boolean retainAll(Collection c):思考:A集合给B集合做交集,交集的元素去哪里?返回值boolean表达什么意思? * 获取功能; *      int size():获取集合中的元素数 *      Iterator<E> iterator():迭代器 * 转换功能: *      Object[] toArray():将集合转换成数组 *  * @author 小鑫 * */public class CollectionDemo {    public static void main(String[] args) {        //创建Collection集合对象        Collection c=new ArrayList();        System.out.println(c);//[] 说明底层重写了toString()        //添加功能:        //boolean add(Object e):给集合中添加指定的元素        //boolean flag = c.add("hello") ;        /**         * 通过查看集合的add()方法,只要给集合中添加元素,永远返回true         *  public boolean add(E e) {            return true;            }         */        c.add("hello");        c.add("world");        //void clear():删除一个集合中的所有元素,暴力删除,(不建议使用)        //c.clear() ;        //boolean remove(Object o):删除一个集合中的指定元素        //System.out.println("remove:"+c.remove("world"));//true        //System.out.println("remove:"+c.remove("java"));//false        //boolean contains(Object o):判断一个集合中是否包含指定的单个元素        System.out.println("contains:"+c.contains("world"));//true        System.out.println("contains:"+c.contains("java"));//false        //boolean isEmpty():判断集合是否为空,如果为空,则返回true        System.out.println("isEmpty:"+c.isEmpty());//false        //int size():获取集合中的元素数        System.out.println("size:"+c.size());//2        System.out.println("c:"+c);//c:[hello, world]    }}

4、集合的高级功能

package org.westos.collection;import java.util.ArrayList;import java.util.Collection;/** * 集合的高级功能: *  boolean addAll(Collection c):添加一个集合中的所有元素 *  boolean removeAll(Collection c):删除一个集合中的所有元素?思考:删除所有算是删除还是删除一个算是删除? *  boolean containsAll(Collection c):判断一个集合中是否另一个集合;思考:是包含一个元素算是包含还是包含所有 *  boolean retainAll(Collection c):思考:A集合给B集合做交集,交集的元素去哪里?返回值boolean表达什么意思? * @author 小鑫 * */public class CollectionDemo2 {   public static void main(String[] args) {      Collection c1=new ArrayList();      Collection c2=new ArrayList();      c1.add("abc1") ;      c1.add("abc2") ;      c1.add("abc3") ;      c1.add("abc4") ;        c2.add("abc1") ;        c2.add("abc2") ;        c2.add("abc3") ;        c2.add("abc4") ;        //c2.add("abc5") ;    //boolean addAll(Collection c):添加一个集合中的所有元素    //System.out.println("addAll:"+c1.addAll(c2));//true    //boolean removeAll(Collection c):删除一个集合中的所有元素?思考:删除所有算是删除还是删除一个算是删除    //删除一个算是删除    // System.out.println("removeAll:"+c1.removeAll(c2));//true    //boolean containsAll(Collection c):判断一个集合中是否另一个集合;思考:是包含一个元素算是包含还是包含所有    System.out.println("containsAll:"+c1.containsAll(c2));//false--->包含所有算是包含    //boolean retainAll(Collection c):思考:A集合给B集合做交集,交集的元素去哪里?返回值boolean表达什么意思?    System.out.println("retianAll:"+c1.retainAll(c2));    //输出每个集合中的元素    /**     *  A集合对B集合取交集,那么交集的元素去A集合里面了,并且返回值boolean表达的意识是A集合中的元素是否发生变化,     *  如果发生变化,就返回true;否则,返回false     */    System.out.println("c1:"+c1);    System.out.println("c2:"+c2);   }}

5、Object[] toArray():将集合转换成数组

package org.westos.collection;import java.util.ArrayList;import java.util.Collection;/** * Object[] toArray():将集合转换成数组 * 需求:给集合中添加String类型的元素,遍历集合 * @author 小鑫 * */public class CollectionDemo3 {  public static void main(String[] args) {    Collection c=new ArrayList();    //给集合中添加元素    c.add("土豆");//c.add(Object obj)---->Object obj=new String("土豆");向上转型了    c.add("地瓜");    c.add("茄子");    c.add("西红柿");    Object[] objs = c.toArray();    for(int i=0;i<objs.length;i++){        //要获取字符串长度:需要使用length(),该方法属于String类的特有功能        //String s = (String) objs[x] ;//向下转型        System.out.println(objs[i]+"---"+((String) objs[i]).length());        /**         * 土豆---2                                地瓜---2                                茄子---2                                西红柿---3         */    }  }}

6、练习

package org.westos.collection_01;import java.util.ArrayList;import java.util.Collection;/** * 需求:有5个学生,每一个学生有自己的信息(姓名,年龄等等),将5个学生的信息遍历出来! *  使用集合的转换功能去遍历学生信息 *   *  1)创建集合对象 *  2)创建5个学生对象 *  3)使用集合添加5个学生对象 *  4)将集合转换成数组:Object[] toArray() ; *  5)遍历数组 * @author 小鑫 * */public class CollectionTest {   public static void main(String[] args) {      Collection c=new ArrayList();      Student s1 = new Student("冬瓜", 25) ;      Student s2 = new Student("西瓜", 22) ;      Student s3 = new Student("南瓜", 28) ;      Student s4 = new Student("黄瓜", 29) ;      Student s5 = new Student("苦瓜", 26) ;      c.add(s1);//Object obj=new Student("");向上转型      c.add(s2);      c.add(s3);      c.add(s4);      c.add(s5);      //将集合转换成数组      Object[] objs = c.toArray();      for(int i=0;i<objs.length;i++){        //使用get()获取学生姓名和年龄        //Student类型接收          Student s=(Student) objs[i];          System.out.println(s.getName()+"---"+s.getAge());      }}}public class Student {  private String name;  private int age;public Student() {    super();}public Student(String name, int age) {    super();    this.name = name;    this.age = age;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}@Overridepublic String toString() {    return "Student [name=" + name + ", age=" + age + "]";}}

这里写图片描述
7、集合的专有遍历方式:迭代器

package org.westos.collection_02;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;/** * 集合的专有遍历方式:使用集合自己本身迭代功能遍历集合中的元素 *   Iterator iterator():迭代器 *      Iterator:迭代器:接口 *          成员方法:Object next()返回迭代的下一个元素:获取功能 *              boolean hasNext():判断一个集合中是否有下一个可以迭代的元素:判断功能 *  * 需求:使用集合存储字符串类型的元素并遍历 * @author 小鑫 * */public class CollectionDemo {   public static void main(String[] args) {     Collection c=new ArrayList();     c.add("hello") ;     c.add("world") ;     c.add("java") ;     c.add("java") ;     //获取迭代器     Iterator it = c.iterator();//底层使用ArrayList中的匿名内部类的形式:接口多态的形式     while(it.hasNext()){         //获取字符串的同时,还要获取字符串长度         //Object obj=it.next();//向下转型         String s=(String) it.next();         System.out.println(s+"---"+s.length());         /**          * hello---5            world---5            java---4            java---4          */     }   }}

8、迭代器原理
这里写图片描述
9、集合的继承体系图
这里写图片描述
10、

package org.westos.collection_02;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class CollectionTest {   public static void main(String[] args) {      Collection c=new ArrayList();      Student s1=new Student("张三",22);      Student s2=new Student("李四",25);      Student s3=new Student("王麻子",27);      //给集合添加元素      c.add(s1);      c.add(s2);      c.add(s3);      //获取迭代器对象      Iterator it = c.iterator();      //遍历      while(it.hasNext()){          Student s=(Student)it.next();          System.out.println(s.getName()+"---"+s.getAge());      }      System.out.println("---------------");      for(Iterator it2 = c.iterator();it2.hasNext();){          Student s = (Student) it2.next() ;          System.out.println(s.getName()+"---"+s.getAge());      }}}public class Student {   private String name;   private int age;public Student() {    super();    // TODO Auto-generated constructor stub}public Student(String name, int age) {    super();    this.name = name;    this.age = age;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}@Overridepublic String toString() {    return "Student [name=" + name + ", age=" + age + "]";}}

这里写图片描述
11、对象数组

package org.westos.objectarray;/** *  * 对象数组:可以存储对象的数组 *  * 需求:有5个学生,每一个学生有自己的信息(姓名,年龄等等),将5个学生的信息遍历出来! *  *      分析:A:定义一个学生类:     *          提供两个成员 变量     *          String name,int age     *          提供无参/有参的构造方法     *          提供set/get()方法 *          B:定义一个学生数组(对象数组) *          C:创建5个学生对象 *          D:赋值,将5个学生对象放到学生数组中 *          E:遍历数组 *          F:输出 * @author 小鑫 * */public class ObjectArrayDemo {   public static void main(String[] args) {     Student[] students=new Student[5];     //创建5个学生对象     Student s1 = new Student("高圆圆", 27) ;     Student s2 = new Student("黄晓明", 28) ;     Student s3 = new Student("邓超" ,30) ;     Student s4 = new Student("孙俪" ,28) ;     Student s5 = new Student("王昭君" ,25) ;     //赋值     students[0] = s1 ;     students[1] = s2 ;     students[2] = s3 ;     students[3] = s4 ;     students[4] = s5 ;     //遍历学生数组     for(int i=0;i<students.length;i++){         //System.out.println(students[i]);         //通过底层原码重写toString()得到的每个对象的成员变量的信息              /* Student [name=高圆圆, age=27]                 Student [name=黄晓明, age=28]                 Student [name=邓超, age=30]                 Student [name=孙俪, age=28]                 Student [name=王昭君, age=25]*/         Student s=students[i];         System.out.println(s.getName()+"---"+s.getAge());        /* 高圆圆---27                               黄晓明---28                               邓超---30                               孙俪---28                               王昭君---25*/     }}}public class Student {  private String name;  private int age;public Student() {    super();    // TODO Auto-generated constructor stub}public Student(String name, int age) {    super();    this.name = name;    this.age = age;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}@Overridepublic String toString() {    return "Student [name=" + name + ", age=" + age + "]";}}

四、List集合

1、用List集合存储字符串类型的元素,并遍历:迭代器遍历

package org.westos.list_01;import java.util.ArrayList;import java.util.Iterator;import java.util.List;/** * 用List集合存储字符串类型的元素,并遍历:迭代器遍历 * List集合是一个有序的集合(存储元素和取出元素是一致的!) *      该集合中的元素是可以重复的 * @author 小鑫 * */public class ListDemo {   public static void main(String[] args) {      List list=new ArrayList();      //添加元素      list.add("hello") ;      list.add("world") ;      list.add("java") ;      //获取迭代器      Iterator it = list.iterator();      while(it.hasNext()){          String s=(String)it.next();          System.out.println(s);          /**           * hello           * world           * java           */      }}}

2、List集合的特有功能

package org.westos.list_02;import java.util.ArrayList;import java.util.List;/** * List集合的特有功能: *      添加功能: *          void add(int index, Object element)在列表的指定位置插入指定元素 *      删除功能: *          Object remove(int index)移除列表中指定位置的元素,返回被删除的元素 *      获取功能: *          ListIterator listIterator():列表迭代器:List集合的专有遍历方式 *          Object get(int index)返回列表中指定位置的元素。 *      替换 *           set(int index,Object element)用指定元素替换列表中指定位置的元素 * @author 小鑫 * */public class ListDemo {   public static void main(String[] args) {      List list=new ArrayList();      //添加元素      list.add("hello");      list.add("world");      list.add("java");      //void add(int index, Object element)在列表的指定位置插入指定元素,在指定位置前面插入一个新的元素      //list.add(1, "javaweb");      System.out.println(list);//[hello, javaweb, world, java]      //Object remove(int index)移除列表中指定位置的元素,返回被删除的元素      //IndexOutOfBoundsException:角标越界了      //System.out.println("remove:"+list.remove(3));      //System.out.println("remove:"+list.remove(2));      // System.out.println("remove:"+list.remove(5));//角标越界      //set(int index,Object element)用指定元素替换列表中指定位置的元素      System.out.println("set:"+list.set(1, "JavaSE"));//set:world      System.out.println("get:"+list.get(1)) ;//get:JavaSE      System.out.println("list:"+list);//list:[hello, JavaSE, java]   }}

3、List集合的遍历方式

package org.westos.list_02;import java.util.ArrayList;import java.util.Iterator;import java.util.List;/** * List集合的遍历方式 *          1)toArray() *          2)Collection集合中的Iterator iterator(); * @author 小鑫 * */public class ListDemo2 {    public static void main(String[] args) {        List list=new ArrayList();        //添加元素        list.add("hello") ;        list.add("java") ;        list.add("hello") ;        list.add("javaweb") ;        list.add("hello") ;        list.add("python") ;        /*        //获取集合中的元素        System.out.println(list.get(0));        System.out.println(list.get(1));        System.out.println(list.get(2));        System.out.println(list.get(3));        System.out.println(list.get(4));        System.out.println(list.get(5));*/        //for循环遍历list集合,使用size()和get()相结合        for(int i=0;i<list.size();i++){            String s=(String)list.get(i);            System.out.println(s+"---"+s.length());        }        System.out.println("---------------");        //获取迭代器对象        Iterator it = list.iterator();        while(it.hasNext()){            String s=(String) it.next();            System.out.println(s+"----"+s.length());        }    }}

这里写图片描述
4、 List集合的列表迭代器及逆向遍历

package org.westos.list_02;import java.util.ArrayList;import java.util.List;import java.util.ListIterator;/** * List集合的列表迭代器 *      ListIterator listIterator() *      列表迭代器接口中有以下几个方法: *          boolean hasNext():判断是否有下一个可以迭代的元素(正向遍历) *          Object next():如果有可以遍历的元素,就获取这个元素 *  *          boolean hasPrevious():判断是否有上一个可以迭代的元素(逆向遍历) *          Object  previous():如果有上一个可以迭代的元素,就获取上一个元素 *      注意: *          要使用逆向遍历,前提必须有正向遍历存在,直接使用逆向遍历,没有意义! * @author 小鑫 * */public class ListDemo3 {   public static void main(String[] args) {      List list=new ArrayList();      //添加元素      list.add("hello");      list.add("java");      list.add("world");      //获取列表迭代器      ListIterator it = list.listIterator();      while(it.hasNext()){          String s=(String)it.next();          System.out.println(s);          }      System.out.println("--------------");      //boolean hasPrevious():判断是否有上一个可以迭代的元素(逆向遍历)      //Object  previous():如果有上一个可以迭代的元素,就获取上一个元素          while(it.hasPrevious()){              String s1=(String)it.previous();              System.out.println(s1);      }   }}

这里写图片描述
5、

package org.westos.list_02;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.ListIterator;/** * 问题? *      我有一个集合,如下,请问,我想判断里面有没有"world"这个元素, *          如果有,我就添加一个"javaee"元素,请写代码实现 *  并发(同一个时间点),并行(同一个时间段) *java.util.ConcurrentModificationException:并发修改异常:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。 *  原因:当前我们用迭代器去遍历元素,使用集合添加的元素,对于迭代器不知道集合添加了这个元素,所以会发生这个异常 *  描述:使用迭代器去遍历集合,是不能直接集合添加元素! *  解决方案: *          1)使用迭代器遍历集合,使用迭代器添加元素 *          2)使用集合遍历,使用集合添加元素 * @author 小鑫 * */public class ListTest {   public static void main(String[] args) {      List list=new ArrayList();      //添加元素      list.add("hello");      list.add("world");      list.add("java");     /* Iterator iterator = list.iterator();      while(iterator.hasNext()){          String s = (String)iterator.next() ;          if("world".equals(s)){              list.add("javaee");          }          //该迭代器不能添加元素      }*/      //方案1:1)使用迭代器遍历集合,使用迭代器添加元素      // Iterator iterator = list.iterator();//该迭代器中没有添加功能,List集合中的专有遍历方式:列表迭代器有添加功能:add(Object obj)      ListIterator it = list.listIterator();      while(it.hasNext()){          String s=(String)it.next();          if("world".equals(s)){             it.add("javaee");          }      }      System.out.println(list);//[hello, world, javaee, java]      //方案2:2)使用集合遍历(普通for循环size()和get()相结合),使用集合添加元素      /*for(int i=0;i<list.size();i++){          String s=(String)list.get(i);          if("world".equals(s)){              list.add("javaee");//在末尾添加          }      }*/      System.out.println(list);//[hello, world, javaee, java]}}