Java第四周

常用类之Object (重点)

1)public int hashCode():
获取对象的hash码值—>支持散列表(支持key-value键值对)

hashCode()(哈希算法 hash table)“理解为地址值”,不是真实地址值,每一个对象的hash码值不同
2)String toString():返回对象的字符串表示形式,结果应该是一个更容易让人读懂的信息表达式(建议所有的子类都覆盖这个方法)
快捷键: idea—>alt+ins---->toString

public class ObjectDemo {public static void main(String[] args) {//创建两个学生Student s1 = new Student() ;Student s2  = new Student() ;System.out.println(s1.hashCode());System.out.println(s2.hashCode());System.out.println("ammmaaa1".hashCode()) ;System.out.println("a1".hashCode());System.out.println("中国".hashCode());System.out.println("----------------------------------------------");//String toString():返回对象的字符串表示形式,结果应该是一个更容易让人读懂的信息表达式(建议所有的子类都覆盖这个方法)//创建一个学生Student student = new Student("圆圆",44,"女") ;System.out.println(student) ;//com.qf.object_01.Student@14ae5a5:地址值针对开发中没有用//直接输出对象名称和使用对象名.toString() 是等价System.out.println(student.toString());/**** Object的toString 的原码*   public String toString() {*         return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());*     }*///Class c = student.getClass() ;//获取这个类的字节码文件对象  class com.qf.object_01.Student//Class---->public String getName(): 获取字节码对象中的全限定名称 (包名.类名)//System.out.println(c) ;//System.out.println(c.getName()+"@"+Integer.toHexString(student.hashCode()));//Integer---->public static String toHexString(int类型)--->int类型数据--->十六进制的字符串 表现形式//System.out.println(Integer.toHexString(642672));}}

public boolean equals(Object obj):指定其他对象与此对象是"相等"
==和equals()方法区别?
==:比较两个基本类型,数据值是否相等
==:连接是两个引用类型,比较的是地址值是否相等
而Object的equals方法,默认比较的是两个引用类型的地址值是否相等,建议子类需要重写这个equals(),重写之后比较的是
两个对象的成员信息是否相同!(Java中所有类都会重写!) ,重写equals方法,必须同时重写hashCode()方法
重写equals:比较每一个对象的成员信息是否相同 如果一样,还要比较每一个成员信息 hashCode()哈希码值是否一样,如果都相同,系统认为这个两个人是一样的!
快捷键: alt+ins—>equals and hashcode方法

public class ObjectDemo2 {public static void main(String[] args) {//两个基本类型 : == 比较两个数据值是否相等!//创建两个学生对象Student s1 = new Student("高圆圆",25,"女") ;Student s2 = new Student("高圆圆",25,"女") ;System.out.println(s1==s2) ;//falseSystem.out.println(s1.equals(s2)); //false  (没有重写比较地址值是否相等)//true :重写Object的equals方法比较是内容是否相同/*** Object的equals方法源码*  public boolean equals(Object obj) {    s1.equals(s2)*         return (this == obj);            return s1 ==s2; //默认比较地址值*     }*/}
}

Object的克隆方法:
protected Object clone() throws CloneNotSupportedException 创建对象并返回它的"副本"
方法里面本身就会带有CloneNotSupportedException:克隆不支持的异常(当要对某个Object的类进行克隆
如果这个类不能实现cloneable接口,那么就会出现这个异常)

public class ObjectDemo3 {public static void main(String[] args) throws CloneNotSupportedException {//没有使用clone之前://创建一个学生对象Student s1 = new Student("圆圆",44,"女") ;System.out.println(s1);//定义一个Student类型的变量s3//将s1赋值给s3Student s3 = s1 ;System.out.println(s3) ;System.out.println("----------------------------------------") ;//Object提供了一个clone方法 来完成复制一个副本Student s4 = new Student("文章",35,"男") ;System.out.println(s4);Object obj = s4.clone();//调用者必须处理本身带有异常的方法System.out.println(obj) ;}
}

Scanner 类

java.util.Scanner:文本扫描器
构造方法:public Scanner(InputStream source) 创建键盘录入对象创建一个文本扫描器Scanner 对象名 = new Scanner(System.in) ;
--->System类---变量名public static final InputStream in成员方法:nextXXX():获取功能
public int nextInt() :录入int类型
public String nextLine() ;录入String类型判断功能:public boolean hasNextInt():判断录入的下一个数据是否为int类型,是,返回true,否则false
public boolean hasNextLine():判断录入的下一个数据为一行内容
键盘录入的时候
先录入int,在录入String ----nextLine() ,这块会出现被漏掉("回车符号")
解决方案:
1)在第一个录入int之后,重新创建一个新的键盘录入对象Scanner ,然后在使用nextLine()
2)在录入String---- String next()
public class ScannerDemo {public static void main(String[] args) {//需要输入流(io流后面讲)InputStream input = System.in ;//public Scanner(InputStream source)//创建文本扫描器对象Scanner sc = new Scanner(input) ;   //形式参数需要输入流--->System.inSystem.out.println("请输入一个数据:");//boolean hasNextXXX():判断录入的下一个是否为XXX类型if(sc.hasNextInt()){//录入下一个为int类型int number = sc.nextInt() ;//InputMismatchException:输入类型和结果不匹配!System.out.println("number:"+number);}else if(sc.hasNextLine()){String line = sc.nextLine() ;System.out.println("line:"+line);}else{System.out.println("目前不提供这个类型的方法...");}}
}

String类

String类: 这个类final修饰不能被继承
字符串是不变; 它们的值在创建后不能被更改(字符串是一个常量,存储在常量池中)

String构造方法:

构造方法:
public String():空字符串 类似于 String s = “” ;
public String(String original):构造一个字符串对象,里面指定一个字符串常量值
public String(byte[] bytes) :使用平台默认字符集(idea默认utf-8)解析解码—>字节数组—>字符串
String(byte[] bytes, int offset, int length) :将一部分字节数组构造成字符串
public String(char[] value):将字符数组—构造成String
public String(char[] value,int offseet,int len):将一部分字符串数组构造成字符串

public class StringDemo {public static void main(String[] args) {//测试//创建一个字符串 public String()String s1 = new String() ;System.out.println("s1:"+s1) ;//不是地址值,String类重写了Object的toString方法System.out.println(s1.length());System.out.println();System.out.println("--------------------------------------------------") ;// public String(String original):构造一个字符串对象,里面指定一个字符串常量值String s2= new String("helloworld") ;System.out.println("s2:"+s2) ;System.out.println(s2.length());System.out.println("----------------------------------------------------");// public String(byte[] bytes) :使用平台默认字符集(idea默认utf-8)解析解码--->字节数组--->字符串byte[] bytes = {97,98,99,100,101} ;String s3 = new String(bytes) ;System.out.println("s3:"+s3) ; //abcde 将字节数组中每一个数字,转成ASCII码表对应的字符System.out.println(s3.length());
//        String(byte[] bytes, int offset, int length) :将一部分字节数组构造成字符串String s4 = new String(bytes,0,2) ;System.out.println("s4:"+s4) ;System.out.println(s4.length());System.out.println("----------------------------------------------------");/* public String(char[] value):将字符数组---构造成Stringpublic String(char[] value,int offseet,int len):将一部分字符串数组构造成字符串*/char[] chs = {'爱','高','圆','圆'} ;String s5 = new String(chs) ;System.out.println("s5:"+s5) ;System.out.println(s5.length());String s6 = new String(chs,1,3) ;System.out.println("s6:"+s6) ;System.out.println(s6.length());//实际开发中,创建字符串不会用上这些格式// String s7 = new String("JavaEE") ;String s8 = "JavaEE" ;//开发中推荐的格式}
}

面试题:
数组中没有length(),字符串有没有length(),集合中没有有length()?
数组 没有length(),length属性 数组对象.length
字符串有length(),
集合没有,获取集合中 元素数 size()
面试题:
String s = new String(“hello”) ;
和String s = “hello” ; 有什么区别?分别创建了几个对象?
区别
前者:在堆内存中开辟空间,然后字符串值常量—指向常量池, 两个对象
后者:推荐的方式,直接常量赋值,直接在常量池中找,有就返回地址,没有,开辟常量空间!

public class StringDemo2 {public static void main(String[] args) {String s1 = new String("hello") ;String s2 = "hello" ;  //====> 拆分char[] chs = {'h','e','l','l','o'} --->String s2 = new String(chs)System.out.println(s1==s2) ; //falseSystem.out.println(s1.equals(s2)) ;//trueString s3=  "helloworld" ;String s4=  "HelloWorld" ;System.out.println(s2.equals(s3)) ;System.out.println(s3.equals(s4)) ;/**** String类已经重写 了Object的equals方法* class String{**      private final char value[];** public boolean equals(Object anObject) {  //s1.equals(s2)  //Object anObject =new String(字符数组)*         if (this == anObject) {   //判断s1和s2地址值是否相同*             return true;*         }*         if (anObject instanceof String) {   // 成立,*             String anotherString = (String)anObject;  //向下转型 String类型*             int n = value.length;                //int n  = s1.value.length= s1.length  = 5*             if (n == anotherString.value.length) {   //if(n == s2.length)    成立*                 char v1[] = value;                   //v1[] = {'h','e','l','l','o'} ;*                 char v2[] = anotherString.value;     //v2[] = {'h','e','l','l','o'} ;*                 int i = 0;                           //统计变量 0*                 while (n-- != 0) {*                     if (v1[i] != v2[i])                 if(v1[0] !=v2[0])---->return false*                         return false;*                     i++;                         //0--->1*                 }*                 return true;*             }*         }*         return false;*     }*   }*/}
}

String类相关的获取功能
1)public char charAt(int index) :获取指定索引处的字符
2)int length():获取字符串的长度
3)public String concat(String str)拼接功能-- 将一个字符串拼接到指定字符串的后面(末尾追加)
4)public String substring(int beginIndex):截取—>从指定位置开始截取,默认截取到末尾结束!
public String substring(int beginIndex, int endIndex) 截取—>从指定位置开始截取到指定位置结束
包前不包后(包含第一个位置,不包含最后一个位置,只能取到endIndex-1处)
5)public String[] split(String regex):拆分(分割) ,按照指定的分割符将字符串拆分成字符串数组
6)public int indexOf(int ch) :返回此字符第一次在字符串中出现的索引值
public int lastIndexOf(int ch):返回此字符最后一次在字符串中出现的索引值

public class StringDemo3 {public static void main(String[] args) {//已知字符串String s = "Java";System.out.println(s.indexOf('a'));System.out.println(s.lastIndexOf('a'));//public char charAt(int index) :获取指定索引处的字符/*System.out.println(s.charAt(0));System.out.println(s.charAt(1));System.out.println(s.charAt(2));System.out.println(s.charAt(3));System.out.println(s.charAt(4));System.out.println(s.charAt(5));*///遍历字符串的每一个字符for(int x = 0 ; x < s.length();x++){char ch = s.charAt(x) ;//获取到获取每一个字符System.out.print(ch+"\t");}System.out.println();System.out.println("-----------------------------------------------");//public String concat(String str)拼接功能-- 将一个字符串拼接到指定字符串的后面(末尾追加)String s2 = "helloworld" ;String s3 = "高圆圆" ;String s4 = s2.concat(s3) ;System.out.println(s4);//需求:已知一个数组,定义一个方法,将数组的元素拼接成Stringint[] arr = {68,29,14,76,5} ;String resultStr = arrayToString(arr) ;System.out.println("resultStr:"+resultStr);System.out.println("-----------------------------------------------");//concat的用法 + substring()+转换功能--- 需求:给定一个字符串,输入"Hellowold" ,输出 "hELLOWORLD"//4)public String substring(int beginIndex):截取--->从指定位置开始截取,默认截取到末尾结束!//      public String substring(int beginIndex, int endIndex) 截取--->从指定位置开始截取到指定位置结束//包前不包后(包含第一个位置,不包含最后一个位置,只能取到endIndex-1处)String s5 = "hellowodl" ;System.out.println(s5.substring(5));System.out.println(s5.substring(5,8));System.out.println("----------------------------------------------------");String str = "JavaEE-Python-Golang-R-C-Php" ;//public String[] split(String regex):拆分(分割) ,按照指定的分割符将字符串拆分成字符串数组String[] strs = str.split("-");//遍历字符串数组for(int x = 0 ; x < strs.length;x++){System.out.print(strs[x]+"\t");}}//定义静态方法,返回值Stringpublic static String arrayToString(int[] arr){//创建一个空串// String s = ""  ;// s += "[" ;//  String s2 = s.concat("[");StringBuffer sb = new StringBuffer() ;sb.append("[") ;//遍历数组for(int x = 0 ; x < arr.length ;x++){//判断最后一个角标if(x==arr.length-1){//拼接最后一个元素//s += arr[x] ;//s += "]" ;sb.append(arr[x]+"]") ;}else{//中间元素// s += arr[x] ;// s += ", " ;sb.append(arr[x] +", ") ;}}return sb.toString() ;}
}

String类的转换功能
1)char[] toCharArray() 将字符串转换成字符数组
2)byte[] getBytes() 平台默认字符集编码(String—>byte[]) 和
byte[] getBytes(String charset):指定的字符集进行编码
String(byte[] bytes) :(bytes[]—>String ) 平台默认字符集解码
String(byte[] bytes,String charset) :(bytes[]—>String ) 指定字符集解码
3)public String toLowerCase():将字符串转换成小写
public String toUpperCase():将字符串转换成大写
4)万能方法: 可以将任何数据类型---->String
public static String valueOf(int i/float…Object)
编码和解码必须一致,否则乱码!

public class StringDemo4 {public static void main(String[] args) throws UnsupportedEncodingException {String s = "helloworld" ;//char[] toCharArray() 将字符串转换成字符数组char[] chs = s.toCharArray();//{'h','e','l','l','o','w','o','r','l','d'}//Arrays:数组工具类---toString(任意类型数组)--转换成StringString resultStr = Arrays.toString(chs);System.out.println(resultStr) ;System.out.println("--------------------------------------");//byte[] getBytes() 平台默认字符集编码(String--->byte[])   和// byte[] getBytes(String charset):指定的字符集进行编码String s2 = "我爱中国" ;byte[] bytes = s2.getBytes(); //平台字符集 utf-8 (一个中文对应三个字节)//System.out.println(bytes);地址值System.out.println(Arrays.toString(bytes));//解码 bytes[]--->String// String(byte[] bytes) :(bytes[]--->String  ) 平台默认字符集解码// *      String(byte[] bytes,String charset) :(bytes[]--->String  ) 指定字符集解码// String s3 = new String(bytes,"gbk") ;//gbk:一个中文对应两个字节// String s3 = new String(bytes,"utf-8") ;//gbk:一个中文对应两个字节String s3 = new String(bytes) ;System.out.println(s3) ;System.out.println("--------------------------------");//public String toLowerCase():将字符串转换成小写//public String toUpperCase():将字符串转换成大写System.out.println(s.toUpperCase());String s4 = "JAVAEE" ;System.out.println(s4.toLowerCase());System.out.println("--------------------------------") ;//已知int--->Stringint i = 100 ;//public static String valueOf(int i/float....Object)String s5 = "" ;System.out.println(s5+=i) ;String s6 = String.valueOf(i);//"100"System.out.println(s6); //"100"}
}

String的判断/替换/去除两端空格 (了解)相关功能
判断功能:
boolean contains(String str):判断大串中是否包含指定子字符串
boolean endsWith(String suffix):判断是否以指定结尾的字符串
public boolean startsWith(String prefix):判断是否指定的字符串开头
boolean equals(Object anObject)。:比较两个字符串内容是否相同
boolean equalsIgnoreCase(String anotherString) :不区分大小写比较两个字符串是否相同
public boolean isEmpty():判断字符串是否空 ,长度为0,true
空串,和空对象? 一样吗?
不一样
public String replace(char oldChar,char newChar) :替换功能
public String trim() :去除字符串两端空格 (一般io流中: 文件读写文件)

public class StringDemo {public static void main(String[] args) {//String s1 = "" ;  //空字符串// String s2 = null ; //空对象 (没有值)//  boolean contains(String str):判断大串中是否包含指定子字符串String s = "helloworldjavaee";System.out.println(s.contains("owo"));System.out.println(s.contains("ak47"));System.out.println("--------------------------------------------") ;/*** boolean endsWith(String suffix):判断是否以指定结尾的字符串* public boolean startsWith(String prefix):判断是否指定的字符串开头*/System.out.println(s.endsWith("ee"));System.out.println(s.startsWith("he"));System.out.println(s.startsWith("高圆圆"));System.out.println("--------------------------------------------") ;/***  boolean equals(Object anObject)。:比较两个字符串内容是否相同*  boolean equalsIgnoreCase(String anotherString) :不区分大小写比较两个字符串是否相同*/String s2 = "helloWorldJavaEE" ;System.out.println(s.equals(s2));System.out.println(s.equalsIgnoreCase(s2));System.out.println("--------------------------------------------") ;// public boolean isEmpty():判断字符串是否空 ,长度为0,trues2 = "" ;System.out.println(s2.isEmpty());
//        public String replace(char oldChar,char newChar)  :替换功能
//        public String trim() :去除字符串两端空格 (一般io流中:  文件读写文件)System.out.println(s.replace("l","*")) ;System.out.println("---------------------------------------------") ;// public String trim() :去除字符串两端空格 (一般io流中:  文件读写文件)String str = " hello           " ;System.out.println(str+"----");String str2 = str.trim();System.out.println(str2+"----");}
}

面试题
String s1 = “hello”;
String s2 = “hel” ;
按照字典顺序比较,它的结果是多少? 考察的就是compareTo的源码
public int compareTo(String anotherString):两个字符串按照字典顺序比较!

两个字符串进行字典顺序比较,先算出长度,取出最小值,然后比较每一个字符,如果这俩个字符串的第一个字符都不相同
使用前面的字符和后面的的字符进行相减(ASII码表的值相减)
如果长度的最小值,在循环遍历两个字符串的每一个字符之前,都相同,直接是两个字符串长度相减!

public class StringTest {public static void main(String[] args) {String s1 = "hello";String s2 = "hel" ;String s3 = "abc" ;System.out.println(s1pareTo(s2));System.out.println(s1pareTo(s3));}
}

StringBuffer

StringBuffer:线程安全的类,支持可变字符序列!
线程–>依赖于进程,线程执行的最小单元! (这周多线程讲)
线程安全----->意味着 “同步”---->执行效率低
举例: 银行类的网站/医院平台
线程不安全----> “不同步”---->执行效率高
构造方法:
public StringBuffer() —>空参构造,初始容量16个字符
public StringBuffer(int capacity)—>指定容量大小的字符串字符串缓冲区(很少用)
public StringBuffer(String str)—>将指定的字符串内容构造到字符串缓冲区中,容量=当前str的长度+16
int length()获取字符串缓冲区长度
int capacity() :获取容量大小

public class StringBufferDemo {public static void main(String[] args) {// public StringBuffer()  --->空参构造,初始容量16个字符StringBuffer sb = new StringBuffer() ;System.out.println("sb:"+sb) ;System.out.println(sb.length()) ;System.out.println(sb.capacity());System.out.println("---------------------------------------") ;//public StringBuffer(int capacity)--->指定容量大小的字符串字符串缓冲区StringBuffer sb2 = new StringBuffer(20) ;System.out.println("sb2:"+sb2) ;System.out.println(sb2.length()) ;System.out.println(sb2.capacity());System.out.println("---------------------------------------") ;// public StringBuffer(String str)--->将指定的字符串内容构造到字符串缓冲区中,容量=当前str的长度+16StringBuffer sb3 = new StringBuffer("高圆圆") ;//--->创建一个字符缓冲区char[]--->将里面的字符串--->append(str)System.out.println("sb3:"+sb3) ;System.out.println(sb3.length());System.out.println(sb3.capacity());}
}

StringBuffer的追加和插入

/*** StringBuffer的追加和插入*       public StringBuffer append(任意Java类型):将指定的类型追加字符串缓冲区的序列中,返回自己本身*       public StringBuffer insert(int index,String str/可以任意Java类型) 在指定位置处插入指定的数据,返回字符串缓冲区本身*** StringBuufer的获取功能*          public char charAt(int index):获取字符串缓冲区中指定位置的字符,返回指定的字符* StringBuffer的删除*          StringBuffer delete(int start, int end)  :删除从指定位置开始到指定位置结束(end-1)的字符,返回字符串缓冲区本身*          StringBuffer deleteCharAt(int index):删除指定位置处的字符,返回值字符串缓冲区本身*StringBuffer的替换功能:*          public StringBuffer replace(int start,int end,String str)*                      将字符串缓冲区中的从指定位置开始到指定位置结束(end-1)的字符序列使用指定的字符串进行替换**StringBuffer的截取功能:*            public String substring(int beginIndex)*            public String substring(int beginIndex,int endIndex)***/
public class StringBufferDemo2 {public static void main(String[] args) {//创建一个字符串缓冲区StringBuffer sb  = new StringBuffer() ;System.out.println("sb:"+sb);// public StringBuffer append(任意Java类型):将指定的类型追加字符串缓冲区的序列中//StringBuffer sb1 = sb.append(100);// StringBuffer sb2 = sb1.append("hellworld");// StringBuffer sb3 = sb2.append('a');// System.out.println(sb3);sb.append(100).append("helloworld").append('A').append(true).append(new Object()) ;System.out.println("sb:"+sb);System.out.println("----------------------------------------") ;StringBuffer sb2 = new StringBuffer() ;sb2.append("hello") ;sb2.append("world") ;sb2.append("javaee") ;System.out.println("sb2:"+sb2) ;// public char charAt(int index):获取字符串缓冲区中指定位置的字符System.out.println(sb2.charAt(4));System.out.println("------------------------------------------") ;//StringBuffer delete(int start, int end)  :删除从指定位置开始到指定位置结束(end-1)的字符,返回字符串缓冲区本身//StringBuffer deleteCharAt(int index):删除指定位置处的字符,返回值字符串缓冲区本身System.out.println(sb2.delete(5,8));System.out.println(sb2.deleteCharAt(5));System.out.println("---------------------------------------------") ;//public StringBuffer insert(int index,String str/可以任意Java类型) 在指定位置处前面插入指定的数据System.out.println(sb2.insert(5,"高圆圆"));System.out.println("----------------------------------------------") ;//public StringBuffer replace(int start,int end,String str)System.out.println(sb2.replace(8,13,"你好"));}
}

StringBuffer的特有功能:

/*** StringBuffer的特有功能:* public StringBuffer reverse()将字符串缓冲区中的字符序列进行反转** 键盘录入一个字符串,判断字符串是否为对称字符串?  true/false*          "abmba"*  分析:*      1)键盘录入一个字符串*      2)将字符串---->char[] toCharArray 字符数组*      3)将字符数组 chs[0]  ---  chs[数组长度-1]*                 chs[1] ---- chs[数组长度-2]*                 ...*                保证数组长度/2**/
public class StringBufferDemo3 {public static void main(String[] args) {//创建键盘录入对象Scanner sc = new Scanner(System.in) ;//提示并录入数据System.out.println("请您输一个字符串数据:" );String line = sc.nextLine() ;//调用功能boolean flag = compareString(line);System.out.println(flag);System.out.println("---------------------------------------------") ;boolean flag2 = compareString(line);System.out.println(flag);System.out.println("---------------------------------------------");//StringBuffer的reverse反转StringBuffer sb = new StringBuffer() ;System.out.println("sb:"+sb) ;sb.append("hello");sb.append("world") ;System.out.println("sb:"+sb);sb.reverse() ;System.out.println("sb:"+sb);System.out.println("---------------------------------------------");boolean flag3 = compareString3(line);System.out.println(flag3);}//方式3:利用StringBuffer的反转功能,结合StringBuffer和String类型转换public static boolean compareString3(String s){//分步走//1)创建一个字符串缓冲区/*StringBuffer sb = new StringBuffer() ;//2)将s追加到缓冲区中sb.append(s) ;//3)将字符串字符缓冲区中的字符序列反转StringBuffer sb2 = sb.reverse();//4)将sb2缓冲区---转换成StringString str = sb2.toString();//5)使用反转之的最终的字符串结果和s进行比较 equalsreturn str.equals(s) ;*///一步走return new StringBuffer(s).reverse().toString().equals(s) ;}//方式2: 将字符串--->字符数组//遍历每一个字符,for里面两个索引,起始start和最终索引startpublic static boolean compareString2(String s){char[] chs = s.toCharArray();for(int start =0,end = chs.length-1; start<end;start++,end--){//chs[start]   chs[end]if(chs[start]!=chs[end]){return false ;}}return true ;}//方式1public static boolean compareString(String s){//1)将s---->转换成字符数组char[] chs = s.toCharArray();/*** 将字符数组 chs[0]  ---  chs[数组长度-1]*                   chs[1] ---- chs[数组长度-2]*                   ...*                  保证  数组长度/2*/for(int x = 0 ; x < chs.length/2;x++){//判断//chs[0]    chs[chs.lengh-1-0]//chs[1]    chs[chs.lengh-1-1]if(chs[x] != chs[chs.length-1-x]){return false ;}}return true ;}
}

类型转换

/*** 在实际开发中,牵扯很多类型之间的相互转换*      将A类型-->B类型,因为想去使用B类型的功能*      但是又可能将B类型--->A类型,最终需求的结果是A类型**  String---->StringBuffer*  StringBuffer---->String*/
public class StringBufferDemo4 {public static void main(String[] args) {//String---->StringBufferString s = "hello" ;/* String s = "hello" ;StringBuffer sb = s ;*/ //两个类型不匹配//方式1 :使用StringBuffer(String str)有参构造StringBuffer sb = new StringBuffer(s) ;System.out.println("sb:"+sb) ;System.out.println("-----------------------------------") ;//方式2:使用StringBuffer()空参构造,结合append(String str)追加StringBuffer sb2 = new StringBuffer() ;sb2.append(s) ;System.out.println("sb2:"+sb2);System.out.println("---------------------------------------------")//StringBuffer---->StringStringBuffer buffer = new StringBuffer("helloJavaEE") ;//方式1:StringBuffer--->public String toString()String str = buffer.toString();System.out.println(str) ;System.out.println("--------------------------------------------") ;//方式2:String类----->构造方法public String(StringBuffer buffer)String str2 = new String(buffer) ;System.out.println(str2);}
}

String和StringBuffer/StringBuilder的区别?

/*** String和StringBuffer/StringBuilder的区别?*      String:是一个常量,一旦被赋值,其值不能被更改 ,不可变的字符序列!*           作为形式参数,形式参数的改变不影响实际参数(和基本类型作为形式参数传递的效果一致 ,特殊的引用类型)*      StringBuffer:支持可变的字符串徐磊,线程安全的类--->同步的--->执行效率低*                   StringBuffer的大部分功能--->synchronzied:同步锁(悲观锁)(多线程去讲)*           作为形式参数,形式参数的改变直接影响实际参数*      StringBuilder:和StringBuffer具备相互兼容的API,线程不安全的类---不同步的---->执行效率高*              单线程程序(只考虑效率)中,使用StringBuilder去替代StringBuffer*              多线程环境下(要考虑安全),使用StringBuffer**/
public class StringBufferTest {public static void main(String[] args) {String s = "helloworld" ;//推荐创建字符串的格式System.out.println(s) ;change(s) ;System.out.println(s) ;//helloworldStringBuffer sb = new StringBuffer("helloworld") ;System.out.println(sb) ;change(sb) ;System.out.println(sb) ;//helloworldjavaee}public static void change(StringBuffer sb){//字符串缓冲区类型sb.append("javaee") ;System.out.println(sb) ;}public static void change(String s) {//字符串类型s += "javaee";System.out.println(s) ;//helloworldjavaee}
}

Integer类型

/*** 需求:*     控制台打印int类型的取值范围*              int--->Integer---->静态的常量*                              public static final int MAX_VALUE*                              public static final int MIN_VALUE*     求出100的二进制/八进制/十六进制(使用程序)*                              public static String toBinaryString(int i):将十进制--转换二进制的字符串形式*                              public static String toHexString(int i)将十进制--转换十六进制的字符串形式*                              public static String toOctalString(int i)将十进制--转换八进制的字符串形式*Integer类:包装的int类型的值* 四类八种基本类型---------->包装类类型(引用类型)  :jdk5以后的自动拆装箱*      byte                Byte*      short               Short*      int                 Integer*      long                Long*      float               Float*      double              Double*      char                Character*      boolean             Boolean**      基本类型         引用类型       String**      String         Integer          int***/
public class IntegerDemo {public static void main(String[] args) {//  public static final int MAX_VALUE// public static final int MIN_VALUESystem.out.println(Integer.MIN_VALUE) ;System.out.println(Integer.MAX_VALUE) ;System.out.println("------------------------------------------") ;/*   public static String toBinaryString(int i):将十进制--转换二进制的字符串形式public static String toHexString(int i)将十进制--转换十六进制的字符串形式public static String toOctalString(int i)将十进制--转换八进制的字符串形式*/System.out.println(Integer.toBinaryString(100));System.out.println(Integer.toOctalString(100));System.out.println(Integer.toHexString(100));}
}

Integer的构造方法:

/*** Integer的构造方法:* public Integer(int value) :将int类型数据包装为Integer类型* public Integer(String s)throws NumberFormatException :将字符串类型包装Integer类型,如果字符串非数字字符串,* 就会出现NumberFormatExceptio数字格式化异常** jdk5以后的新特性:自动拆装箱      /静态导入(导入到方法的级别,前提方法必须为静态)/增强for循环/可变参数...*      基本类型会自动装箱为 引用类型:    int-->Integer*      引用类型会拆箱为 基本类型  :     Integer-->int*/
public class IntegerDemo2 {public static void main(String[] args) {//创建一个Integer类对象//public Integer(int value) :将int类型数据包装为Integer类型Integer i = new Integer(100) ;  //将int----Integer类型i += 200 ;                            //将Integer--->int--->在和200相加---->int--->IntegerSystem.out.println(i) ;/** 利用反编译工具类:将上面的字节码文件---反编译* 	Integer i = new Integer(100);//100 装箱 Integer*                                               //public int intValue():Integer--->int 拆箱i = Integer.valueOf(i.intValue() + 200);  // --->(i.intValue()+200)--->300赋值给i*                                       //将一个整数赋值给Integer--->底层执行的Integer.valueOf(300)System.out.println(i);               //输出结果* */System.out.println("---------------------------------------------") ;//public Integer(String s)throws NumberFormatException ://String s = "hello" ; //字符串必须为数字字符串String s = "10" ;Integer ii = new Integer(s) ;System.out.println(ii);//Integer i = 100 ;// Integer i = new Integer(100) ;}
}

int和String的类型转换

/*** 类型转换*      int---->String 静态方法public static String toString(int i)*      String--->int  (使用居多)  public static int parseInt(String s)*                  前后端交互:前端提交的数据几乎String类型*/
public class IntegerDemo3 {public static void main(String[] args) {//int--->Stringint i = 100 ;String result = "" ;//方式1:字符串拼接符号+result += i;System.out.println(result) ;System.out.println("---------------------------------");//方式2:int--->Integer---->String//Integer(int i) ---->publict String toString()Integer ig = new Integer(i) ;String result2 = ig.toString();System.out.println(result2); //"100"System.out.println("---------------------------------");//方式3:Integer的静态方法public static String toString(int i)String result3 = Integer.toString(i);System.out.println(result3);System.out.println("--------------------------------------") ;// String---->intString s = "20" ; //数字字符串//方式1:String--->Integer --->public int intValue()Integer ig2 = new Integer(s) ;int value = ig2.intValue();System.out.println(value); //20System.out.println("-----------------------------------------") ;//方式2:直接转换public static int parseInt(String s) throws NumberFormatExceptionint value2 = Integer.parseInt(s);System.out.println(value2); //20//parseXXX方法在任意的基本类型对应的类型都存在(万能方法)//String--Long-->long---->Long.parseLong(字符串)//String--Float-->float--->Float.parseFloat(小数字符串)}
}

Character类型

/*** 构造方法*  Character(char value):包装一个char字符类型  char---->Character* 成员方法*      public static boolean isDigit(char ch):判断是否为数字字符*      public static boolean isUpperCase(char ch):判断是否为大写字母字符*      public static boolean isLowerCase(char ch):判断是否为小写字母字符**/
public class CharacterDemo {public static void main(String[] args) {//创建一个Character对象Character character = new Character((char) 97) ;System.out.println(character);Character character2 = new Character('a') ;System.out.println(character2);/*   public static boolean isDigit(char ch):判断是否为数字字符public static boolean isUpperCase(char ch):判断是否为大写字母字符public static boolean isLowerCase(char ch):判断是否为小写字母字符*/System.out.println(Character.isDigit('0'));System.out.println(Character.isDigit('A'));System.out.println(Character.isDigit('a'));System.out.println(Character.isUpperCase('0'));System.out.println(Character.isUpperCase('A'));System.out.println(Character.isUpperCase('a'));}
}

Date类

/*** java.util.Date:特定的日期*      构造方法:*              public Date():系统时间的日期格式*      成员方法:*              public long getTime():获取指定Date对象的系统时间毫秒值*/
public class DateDemo {public static void main(String[] args) {//创建一个Date对象Date date  = new Date()  ;System.out.println(date) ;//       Date日期格式//public long getTime():获取指定Date对象的系统时间毫秒值long time = date.getTime();System.out.println(time);}
}
/*** @author 高圆圆* @date 2022/11/15 15:47* Date日期格式      ----->String日期文本             --->格式化操作**     String日期文本*           2022/11/15  2022年11月15日 ----------->Date (重点 )       ---->解析*      应用场景:用户注册 填写 出生日期  "1995-05-27"   String---->数据库Date格式**  格式化或者解析:使用DateFormat类,它是一个抽象类,不能实例化,用的抽象类的子类SimpleDateFormat**  Date日期个--->String格式化*      public final String format(Date date)*  构造方法*  SimpleDateFormat(String pattern)        * pattern模式  :  y:代表年              yyyy 代表整个年份 :2022*                 M:代表月份                MM       11  07  06*                 d:月份中的日               dd      03 11 01*                 H:0-23(一天的小数数)       HH*                 m:小时的分钟数             mm* String日期文本---->Date 解析* public Date parse(String source)  throws ParseException :*      如果String日期文本 和转换器SimpleDateFormat(String pattern) 里面的模式不匹配就会造成解析异常!*          String s = "2008-5-12"*        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ") ;//解析出问题了!**/
public class DateDemo2 {public static void main(String[] args) throws ParseException {//将Date---->String 格式化//创建一个Date对象,当前系统日期对象Date date = new Date() ;//SimpleDateFormat(String pattern)   :转换器SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;//public final String format(Date date)String dateStr = sdf.format(date);System.out.println(dateStr);System.out.println("---------------------------------------------------") ;//给定一个日期文本 String---->Date (重点)String str = "2020-12-31" ;//中间桥梁
//        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日") ;//模式不匹配SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd") ;//public Date parse(String source)  throws ParseException :Date date2 = sdf2.parse(str);System.out.println(date2);}
}
/*** 自定义一个工具类:---构造私有化,外界不能new*      定义一个两个静态方法** 调用jdk提供的一个类的方法----如果这个方法本身throws 异常类名,我们必须处理!*      处理方式*              1)throws :抛出   (自己玩)*              2)  捕获异常    (开发中)*                  try{**                   可能出现问题的代码*              }catch(异常类名 对象名){*                  对象名.printStackTrice();跟踪堆栈*              }*/
public class DateUtils {private DateUtils(){}/*** 将Date日期格式转换成String文本格式* @param date  转换的日期对象* @param pattern 指定的模式* @return 返回字符串文本格式*/public static String date2String(Date date,String pattern){return new SimpleDateFormat(pattern).format(date) ;}/*** 将String日期文本解析为Date日期对象* @param source  指定的字符串日期文本* @param pattern  指定的模式* @return  返回的日期对象*/public static Date string2Date(String source,String pattern) throws ParseException {return  new SimpleDateFormat(pattern).parse(source) ;}
}

Random:伪随机数生成器

/*** Random:伪随机数生成器*      public Random() 构造方法:创建新的随机数生成器*      public Random(long seed) 构造方法:创建新的随机数生成器(以指定的long 的类型计算随机数):每一次均分布局一样的 (不推荐)*      成员方法*          public int nextInt():获取的int类型的取值范围*          public int nextInt(int n):[0,n)随机数*/
public class RandomDemo {public static void main(String[] args) {//使用Random类产生随机数Random random = new Random() ;//10个随机数for(int x = 0 ; x < 10 ; x++){// int n = random.nextInt();int n = random.nextInt(100);System.out.println(n);}}
}
/*** System类: 不能实例化*      三个成员变量 ---静态常量*          static PrintStream err“标准”错误输出流。*          static InputStream in“标准”输入流。   (InputStream:字节输入流 --读数据)*          static PrintStream out  “标准”输出流。(PrintStream字节打印流--->*          OutputStream字节输出流---写/打印)**成员方法*  public static long currentTimeMillis():获取系统时间毫秒值(应用场景:计算程序的执行效率)*  public static void exit(int status):参数为0,正常终止jvm*  public static void gc():手动开启垃圾回收器*           开启垃圾回收器,会调用Object类的finalize()垃圾回收方法*  public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)  :复制数组*              参数1:原数组*              参数2:原数组中的某个位置*              参数3:目标数组*              参数4:目标数组中的某个位置*              参数5:从原数组的那个位置srcPos指定长度复制到目标数组中**/
public class SystemDemo {public static void main(String[] args) {//System.err.println("错误信息");PrintStream ps =  System.out ;  //返回字节打印流:是字节输出流的一种(io流中)//PrintStream---->public void print(任意java类型的数据)/public void println(任意java类型 数据)ps.println("helloworld");//System.out.println("helloworld");System.out.println("----------------------------------------------") ;//public static long currentTimeMillis():获取系统时间毫秒值(应用场景:计算程序的执行效率)long start =System.currentTimeMillis() ;for(int x = 0 ; x < 10000; x ++){System.out.println(x+"hello") ;}// public static void exit(int status):参数为0,正常终止jvm//System.exit(0);long end =System.currentTimeMillis() ;System.out.println("共耗时:"+(end-start)+"毫秒");System.out.println("---------------------------------------------") ;//public static void gc():手动开启垃圾回收器//开启垃圾回收器,会调用Object类的finalize()垃圾回收方法Person p = new Person("高圆圆",44) ;System.out.println(p) ;//  p = null ;// 不指定内存空间了, 现在手动开启垃圾回收器// System.gc();System.out.println("---------------------------------------------------") ;/*** public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)  :复制数组*                参数1:原数组*                参数2:原数组中的某个位置*                参数3:目标数组*                参数4:目标数组中的某个位置*                参数5:从原数组的那个位置srcPos指定长度复制到目标数组中*/int[] arr = {1,2,3,4,5} ;int[] arr2 = {6,7,8,9,10} ;//使用Arrays数组工具类toString(数组)--->StringSystem.out.println("复制之前:") ;System.out.println(Arrays.toString(arr));System.out.println(Arrays.toString(arr2));System.out.println("-----------------------------------") ;System.out.println("复制之后:") ;System.arraycopy(arr,1,arr2,1,3);System.out.println(Arrays.toString(arr));System.out.println(Arrays.toString(arr2));}
}

面试题:
final,finalize,finally有什么区别?
final:状态修饰符 表示最终的无法更改的
修饰类,类不能被继承
修饰符成员方法,方法不能被重写
修饰变量,此时常量
finalize是一个方法:Object类的方法---->主要垃圾回收器回收没有更多引用的对象,来释放内存空间
finally:关键字: 捕获异常标准格式 :try{
//可能出现问题的代码
}catch(异常类名 对象名){
//处理异常
}finally{ //释放系统资源(Java底层语言都是c)
//Io流(创建文件/流对象都需要关闭) /jdbc(连接对象,执行对象,查询对象都需要close)
}

BigDecimal:作用针对小数进行精确计算

/***  BigDecimal:作用针对小数进行精确计算构造方法*   BigDecimal(String value):参数 "小数字符串值"*   BigDecimal(int value):整数*   BigDecimal(double 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:scale保留小数位数*              参数3:roundingMode舍入的模式  BigDecimal提供静态常量**/
public class BigDecimalDemo {public static void main(String[] args) {//创建BigDecimal(String value):参数 "小数字符串值"BigDecimal bigDecimal = new BigDecimal("1.05") ;BigDecimal bigDecimal2 = new BigDecimal("0.5") ;/*** public BigDecimal add(BigDecimal augend):加*  public BigDecimal subtract(BigDecimal subtrahend)减*   public BigDecimal multiply(BigDecimal multiplicand)乘*  public BigDecimal divide(BigDecimal divisor):除*/System.out.println(bigDecimal.add(bigDecimal2));System.out.println(bigDecimal.subtract(bigDecimal2));System.out.println(bigDecimal.multiply(bigDecimal2));System.out.println(bigDecimal.divide(bigDecimal2));/*** public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)*              参数1:除数值*               参数2:scale保留小数位数*                参数3:roundingMode舍入的模式  BigDecimal提供静态常量*/System.out.println(bigDecimal.divide(bigDecimal2,2,BigDecimal.ROUND_HALF_UP)); //支持四舍五入}
}

Calendar :日历类

/*** java.util.Calendar :日历类--->是一个抽象类,不能new* 这个类里面的某些功能(静态功能)---一定完了这个类的子类的实例!*      创建日历实例--->public static Calendar getInstance()**  Calendar提供静态的字段(成员变量--->静态常量)*          public static final int DATE:月中的日期值*          public static final int MONTH:年中的月份值  (0-11),获取之后+1*          public static final int YEAR:年份值** Calendar提供成员方法:*          public int get(int field):获取日历的字段值*                      参数就是需要通过Calendar访问的静态常量的那些字段**          public abstract void add(int field,int amount)    给日历字段设置偏移量,添加或者减去 amount值**          public final void set(int year,int month,int date) 设置日历字段**/
public class CalendarDemo {public static void main(String[] args) {//创建日历类对象//public static Calendar getInstance()Calendar c = Calendar.getInstance();System.out.println(c) ;System.out.println("-----------------------------------");//获取当前系统日历的年,月,日.../***  Calendar提供静态的字段(成员变量--->静态常量)*           public static final int DATE:月中的日期值*          public static final int MONTH:年中的月份值*            public static final int YEAR:年份值**   Calendar提供成员方法:*           public int get(int field):获取日历的字段值*                        参数就是需要通过Calendar访问的静态常量的那些字段*///获取年份int year = c.get(Calendar.YEAR) ;//获取月份int month = c.get(Calendar.MONTH)+1 ;//获取月中的日期int day = c.get(Calendar.DATE) ; //DAY_OF_MONTH和DATE通用System.out.println(year+"-"+month+"-"+day);System.out.println("-------------------------------------------") ;//public abstract void add(int field,int amount)    给日历字段设置偏移量,添加或者减去 amount值//5年前的今天c.add(Calendar.YEAR,-5) ; //给年份设置偏移日期//5年前的10天前//给月中日期设置偏移量c.add(Calendar.DATE,-10) ;//获取年份int year2  = c.get(Calendar.YEAR) ;int month2 = c.get(Calendar.MONTH)+1 ;//获取月中的日期int day2 = c.get(Calendar.DATE) ; //DAY_OF_MONTH和DATE通用System.out.println(year2+"年"+month2+"月"+day2+"日") ;System.out.println("----------------------------------------");//public final void set(int year,int month,int date) 设置日历字段c.set(2018,10,20) ;year2  = c.get(Calendar.YEAR) ;month2 = c.get(Calendar.MONTH)+1 ;//获取月中的日期day2 = c.get(Calendar.DATE) ; //DAY_OF_MONTH和DATE通用System.out.println(year2+"年"+month2+"月"+day2+"日") ;}
}

Jdk5里面其他新特性:

/*** Jdk5里面其他新特性:*      1)静态导入---->导入到方法的级别*         import static 包名.类名.方法名;*      前提使用静态导入,这个类的方法必须为静态**      在使用静态导入的时候,导入jdk提供的一些工具类里面静态方法的时候,我们定义的方法不能和它方法名冲突*      如果冲突了,静态导入是不识别,这个时候必须导入全限定名称 :包名.类名.方法名(xxx)**     2)可变参数,当一个方法形式参数不知道多少个,这个时候可以使用可变参数(类似一个数组)*          public  返回值类型 方法名(数据类型... 参数名)*/
import  static java.lang.Math.abs;
import static java.lang.Math.max; //最大值
import static java.lang.Math.min; //最小值
import static java.lang.Math.pow;  //pow(a,b)  a的b次幂
public class JDK5StaticDemo {public static void main(String[] args) {//java.lang.Math:针对数学运算的类//public static double/int abs(double/int a,double/int b):求绝对值//...都是静态成员方法System.out.println(Math.abs(-10));System.out.println(Math.abs(100));System.out.println(java.lang.Math.abs(-100));//使用到了静态导入,方法名和自定义的方法名冲突了System.out.println(max(10,15));System.out.println(min(5,3));System.out.println(pow(2,3));System.out.println("---------------------------------");int sum = add(10, 20, 30, 40, 50);System.out.println(sum) ;}//自定义的abs方法public static void abs(int a){System.out.println(a);}//求多个数据和public  static int add(int...a){//类似一个数组int sum = 0 ;//遍历for(int x = 0 ; x < a.length  ;x++){sum += a[x] ;}return sum ;}
}

集合

Colleciton集合

/*** Colleciton:没有jdk提供直接实现,通过具体的子接口List/Set的子实现类实现** 创建集合的时候<E> :里面存储的引用类型的元素*      模拟数组,创建集合的时候就明确了集合中存储的数据类型,否则导致程序不安全!** 常用基本功能:*      添加*          boolean add(E e):添加元素 E--->Object任意Java元素*      删除*           删除集合中的元素boolean remove(Object o)*           暴力删除(将集合全部清空)void clear()**      判断*              boolean isEmpty():判断集合是否为空*              boolean contains(Object o):判断集合是否包含指定的元素**/
public class CollectionDemo {public static void main(String[] args) {//创建一个Collection,没有带泛型// Collection  c = new ArrayList() ;//创建的集合,带上<泛型>Collection<String> c = new ArrayList<>() ; //new 集合<默认和前面的泛型类型一致,可以不写> () ;  jdk7新特性 泛型推断System.out.println(c);// boolean add(E e):添加元素 E--->Object任意Java元素// boolean flag1 = c.add("hello") ;// boolean flag2 = c.add(100) ;// boolean flag3 = c.add('A') ;/***   public boolean add(E e) {*        ///...中间的逻辑在数据扩容*         return true;*     }*/// System.out.println(flag1+"---"+flag2+"---"+flag3);c.add("hello") ;c.add("world") ;c.add("javaee") ;//c.add(100) ;System.out.println("--------------------------------") ;
//        删除集合中的元素boolean remove(Object o)
//            暴力删除(将集合全部清空)void clear()//System.out.println(c.remove("javaee"));
//        c.clear();//boolean isEmpty():判断集合是否为空// boolean contains(Object o):判断集合是否包含指定的元素// System.out.println(c.isEmpty()) ;System.out.println(c.contains("高圆圆"));System.out.println(c.contains("world"));System.out.println(c);}
}

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

/*** Collection的专有遍历方式:迭代器* Iterator<E> iterator()*          Iterator接口提供了功能:Object next() :获取下一个可以遍历的元素*          boolean hasNext():判断如果迭代器里面有元素,则返回true,然后在获取!**          需求:使用Collection存储String类型,并去使用迭代器将元素一一遍历,打印控制台**  1)使用Collection集合存储5个学生,使用迭代器的这种方式进行遍历!*  2)使用Collection集合存储String类型,如果这个字符串是"world",那么添加一个新的字符串数据"javaEE",*  然后遍历集合中的数据*/
public class CollectionDemo {public static void main(String[] args)  {//创建一个集合对象Collection<String> c = new ArrayList<>() ;//存储String类型的元素c.add("hello") ;c.add("world") ;c.add("java") ;c.add("javaee") ;//Iterator<E> iterator() 获取迭代器Iterator<String> it = c.iterator();// Iterator接口提供了功能:E next() :获取下一个可以遍历的元素//先判断,在获取//boolean hasNext():判断如果迭代器里面有元素,则返回true,然后在获取!/*if(it.hasNext()){//第一次获取String next = it.next();System.out.println(next);}//第二次获取if(it.hasNext()){System.out.println(it.next());}//第三次获取if(it.hasNext()){System.out.println(it.next());}//第四次获取if(it.hasNext()){System.out.println(it.next());}
//        System.out.println(it.next());//java.util.NoSuchElementException 没有元素的异常//第五次获取if(it.hasNext()){System.out.println(it.next());}*///迭代器标准代码while(it.hasNext()){//有下一个元素//再获取String  s = it.next() ;System.out.println(s+"---"+s.length());}}
}

Vector集合

/** Vector集合:线程安全的类(底层结构:数组,查询快,增删慢)* 特有功能:*      public void addElement(E obj)将指定的元素添加Vector集合中(默认追加)*      public Enumeration<E> elements():获取枚举组件接口----->类似于Collection集合的Iterator iterator()*              Enumeration接口**                          boolean hasMoreElements() 判断是否有更多的元素 ----->类似于Iterator里面的boolean hasNext()*                          E  nextElement() :获取下一个元素              ----->类似于Iterator里面的E next()**      public E elementAt(int index):通过索引值获取元素   ---->类似List集合的E get(int index)*      int size():获取集合元素数*/
public class VectorDemo {public static void main(String[] args) {//创建Vector集合Vector<String> v = new Vector<>() ;System.out.println(v) ;// public void addElement(E obj)将指定的元素添加Vector集合中(默认追加)v.addElement("hello") ;v.addElement("hello") ;v.addElement("world") ;v.addElement("javaEE") ;System.out.println(v);System.out.println("------------------------------------------------------") ;// public E elementAt(int index):通过索引值获取元素   ---->类似List集合的E get(int index)//int size():获取集合元素数//特有遍历方式1for(int x = 0 ; x < v.size() ;x++){String s = v.elementAt(x);System.out.println(s);}System.out.println("------------------------------------------------------") ;//特有遍历方式2:/*public Enumeration<E> elements():获取枚举组件接口----->类似于Collection集合的Iterator iterator()*              Enumeration接口**                          boolean hasMoreElements() 判断是否有更多的元素 ----->类似于Iterator里面的boolean hasNext()*                          E  nextElement() :获取下一个元素              ----->类似于Iterator里面的E next()*/Enumeration<String> en = v.elements();while(en.hasMoreElements()){String s = en.nextElement();System.out.println(s);}}
}

LinkedList

/*** LinkedList:*      线程不安全,不同步,执行效率高*     底层数据结构: 线程结构之链表,查询慢,增删快!**     特有功能:*          添加元素*              public void addFirst(E e) 将指定的元素添加到链表的开头*              public void addLast(E e) 将指定的元素添加到链表的末尾*              public E getFirst():获取第一个元素*              public E getLast():获取最后一个元素*              public E removeFirst():删除第一个并返回第一个元素*              public E removeLast():删除最后一个元素并返回***/
public class LinkedListDemo {public static void main(String[] args) {//创建一个链表LinkedList<String> lk = new LinkedList<>() ;//添加字符串lk.add("hello") ;lk.add("world") ;lk.add("java") ;System.out.println(lk) ;/*public void addFirst(E e) 将指定的元素添加到链表的开头*              public void addLast(E e) 将指定的元素添加到链表的末尾*              public E getFirst():获取第一个元素*              public E getLast():获取最后一个元素*              public E removeFirst():删除第一个并返回第一个元素*              public E removeLast():删除最后一个元素并返回*/lk.addFirst("JavaEE"); ;lk.addLast("Android");System.out.println(lk);System.out.println(lk.getFirst());System.out.println(lk.getLast());System.out.println(lk.removeFirst());System.out.println(lk);}
}

Set集合

/*** Set集合:元素唯一的 默认情况使用HashSet进行实例(创建对象)**  HashSet的底层依赖于HashMap(哈希表结构),元素唯一,迭代顺序无法保证的!** HashSet集合保证元素唯一---底层依赖HashMap的put方法---->依赖于hashCode()/equals(),* 而现在存储String类型,重写了equals和hashCode(),保证元素唯一!**/
public class HashSetDemo {public static void main(String[] args) {//创建HashSet集合对象HashSet<String> hs = new HashSet<>() ;//添加元素hs.add("hello") ;hs.add("hello") ;hs.add("world") ;hs.add("world") ;hs.add("java") ;hs.add("java") ;hs.add("javaee") ;//遍历for(String s:hs){System.out.println(s);}}
}

TreeSet集合

/*** TreeSet集合--->Set集合的的实现类,它应该满足保证元素唯一** 底层基于TreeMap<K,V>,它是一个红黑树(red-black-tree)* 有自然排序/比较器排序** 构造方法:*      public TreeSet():创建一个空的树,元素是按照自然排序顺序,里面的元素必须要实现Comparable接口**  现在使用TreeSet存储Integer类型的元素*  结论:*          要实现自然排序,那么使用TreeSet的无参构造方法,而且存的类型一定要实现Comparable接口,重写*          compareTo(T t)方法,完成比较***/
public class TreeSetDemo {public static void main(String[] args) {//创建一个TreeSet集合// public TreeSet():创建一个空的树,元素是按照自然排序顺序,里面的元素必须要实现Comparable接口TreeSet<Integer> ts = new TreeSet<>() ;//添加元素ts.add(17) ;ts.add(19) ;ts.add(20) ;ts.add(22) ;ts.add(18) ;ts.add(18) ;ts.add(23) ;ts.add(23) ;ts.add(16) ;ts.add(24) ;ts.add(24) ;//遍历for(Integer i :ts){System.out.println(i);}}
}

Map集合

/*** 需求:*      通过学生的学号sid,获取学生的信息(姓名....)**  现在使用单列集合Collection<E></>--->List /Set*  List<Student>,本身就是将整个对象存储进去了,获取方式直接获取学生数据,遍历---->判断sid是多少**  所以Java提供 Map<K,V> 键值对(映射项),一个键(必须唯一)对应一个值(值可以重复)**              Key    Value   ---->散列表结构(哈希表)*              1       张三*              2       李四*              3       王五*              4       张三*面试题* Map和Collection的区别 ?*        Collection<E>:单例集合,只能存储一种引用类型数据 遍历方式和Map不同;*        Collection集合的应用范围大:*                      ArrayList*                      Vector*                      LinkedList*        它里面的部分集合和Map有关联(HashSet--->依赖HashMap   / TreeSet---->依赖于TreeMap)*        Map<K,V>,双列集合---->可以存储键值对("夫妻对")*        遍历方式:通用方式 获取所有的键,通过键找值!*         应用范围:*              HashMap---->存储 和 获取 (默认使用)*              TreeMap---->存储---获取(按照排序规则排序)*              Map---->称为 "实体"*                      Map<Integer,Product>**  Map(针对键有效,键必须唯一!)的基本功能*      添加:*          V put(K key, V value):添加键值对元素,返回值什么意思?*                      map针对键有效,键如果唯一的,返回是null;*                      如果重复,将后面的键对应的值把前面的值覆盖了,返回第一次键对应的值*      删除:*          V remove(Object key):删除键,返回键对应的值*          void clear():暴力删除,将map清空掉*      判断:*          boolean containsKey(Object key):判断Map集合是否包含指定的键,包含返回true,否则false*          boolean containsValue(Object value):判断Map集合是否包含指定的值,包含则返回true,否则false*          boolean isEmpty() :判断集合是否为空*/
public class MapDemo {public static void main(String[] args) {//创建Map集合---子实现类HashMapMap<String,String> map  = new HashMap<>() ;System.out.println(map) ;//  V put(K key, V value):添加键值对元素,返回值什么意思?//添加//  String value = map.put("文章", "马伊琍");// System.out.println(value);// String value2 = map.put("文章", "姚笛") ;//  System.out.println(value2);//String value3 = map.put("王宝强", "马蓉");// System.out.println(value3);map.put("文章", "马伊琍");map.put("文章", "姚笛") ;map.put("王宝强", "马蓉");map.put("黄晓明","babay") ;map.put("陈玄风","梅超风") ;System.out.println(map);System.out.println("-----------------------------------------------") ;//V remove(Object key):删除键,返回键对应的值// void clear():暴力删除,将map清空掉System.out.println(map.remove("陈玄风"));//map.clear();//System.out.println(map);System.out.println("-----------------------------------------------") ;
//        boolean containsKey(Object key):判断Map集合是否包含指定的键,包含返回true,否则false (使用居多)
//        boolean containsValue(Object value):判断Map集合是否包含指定的值,包含则返回true,否则false
//        boolean isEmpty() :判断集合是否为空System.out.println(map.containsKey("马保国"));System.out.println(map.containsKey("黄晓明"));System.out.println(map.containsValue("马蓉"));System.out.println(map.containsValue("孙俪"));System.out.println(map.isEmpty()) ;}
}

Map集合遍历

/*** 遍历Map集合的方式*          1)获取所有的键的集合 Set<K> keySet()    (通用的遍历方式)      --->"获取所有的丈夫",丈夫自己妻子*            结合    V get(Object key):通过键找值*          2)Set<Map.Entry<K,V>> entrySet() :获取Map结合的键值对对象    ---->"获取所有结婚",找丈夫,找妻子** HashMap---->put方法---->依赖于hashCode()+equals()方法 能够保证键唯一!* 存储String,String类型重写了hashCode()+equals()方法,比较键的字符串内容是否相同!*/
public class MapDemo2 {public static void main(String[] args) {//创建Map集合Map<String,String> map = new HashMap<>() ;//添加元素map.put("郭靖","黄蓉") ;map.put("杨过","小龙女") ;map.put("陈玄风","梅超风") ;map.put("令狐冲","任盈盈") ;map.put("郭靖","高圆圆") ;/*** 1)获取所有的键的集合 Set<K> keySet()    (通用的遍历方式)      --->"获取所有的丈夫",丈夫自己妻子*           结合    V get(Object key):通过键找值*//* Set<String> keySet = map.keySet() ;for(String key:keySet){//通过键获取值String value = map.get(key);System.out.println(key+"---"+value) ;}*//*** 2)Set<Map.Entry<K,V>> entrySet() :获取Map结合的键值对对象    ---->"获取所有结婚",找丈夫,找妻子*/Set<Map.Entry<String, String>> entry = map.entrySet() ;//遍历所有映射项(一个键->一个值)for(Map.Entry<String, String> en:entry){//K getKey():通过键值对对象,获取键//K getKey():通过键值对获取值String key = en.getKey();String value = en.getValue();System.out.println(key+"---"+value) ;}}
}

Collections:针对集合操作工具类

/** java.util.Collections:针对集合操作工具类*      常用的方法*      二分搜索法,在指定List集合中查询指定元素第一次出现索引值 (集合的元素有序)* public static <T> int binarySearch(List<? extends Comparable<? super T>> list,T key)* public static <T> T max(Collection<? extends T> coll):针对Collection集合获取最大值(自然顺序比较获取最大值)* public static <T> T min(Collection<? extends T> coll):针对Collection集合获取最小值(自然顺序比较获取最小值)* public static void reverse(List<?> list):将List集合的元素反转* public static void shuffle(List<?> list):针对List集合随机置换*** public static <T extends Comparable<? super T>> void sort(List<T> list):针对List集合按照自然顺序排序* public static <T extends Comparable<? super T>> void sort(List<T> list,Comparator<T> com):*  针对List集合按照比较器进行排序****/
public class CollectionsDemo {public static void main(String[] args) {//创建一个List集合List<Integer> list = new ArrayList<>() ;list.add(10) ;list.add(5) ;list.add(25) ;list.add(15) ;list.add(12) ;list.add(35) ;System.out.println(list);//public static <T extends Comparable<? super T>> void sort(List<T> list):针对List集合按照自然顺序排序Collections.sort(list) ;System.out.println(list);// public static <T> int binarySearch(List<? extends Comparable<? super T>> list,T key)System.out.println(Collections.binarySearch(list,12));System.out.println(Collections.binarySearch(list,120));System.out.println("-----------------------------------------------") ;System.out.println(Collections.max(list));System.out.println(Collections.min(list));Collections.shuffle(list) ;System.out.println(list);System.out.println("---------------------------------------------") ;//使用List集合存储员工,然后按照员工的年龄从小到大排序(主要条件)//public static <T extends Comparable<? super T>> void sort(List<T> list,Comparator<T> com):List<Employee> ls  = new ArrayList<>() ;//存储员工对象Employee e1 = new Employee("zhangsan",20) ;Employee e2 = new Employee("wangwu",19) ;Employee e3 = new Employee("zhaoyouting",28) ;Employee e4 = new Employee("wenzhang",28) ;Employee e5 = new Employee("zhangsanfeng",35) ;Employee e6 = new Employee("zhangsanfeng",35) ;Employee e7 = new Employee("mayili",39) ;Employee e8 = new Employee("mayili",30) ;ls.add(e1) ;ls.add(e2) ;ls.add(e3) ;ls.add(e4) ;ls.add(e5) ;ls.add(e6) ;ls.add(e7) ;ls.add(e8) ;//按照员工的年龄从小到大Collections.sort(ls, new Comparator<Employee>() {//比较器实现@Overridepublic int compare(Employee e1, Employee e2) {int num = e1.getAge() - e2.getAge() ;int num2 = (num==0)?(e1.getName()pareTo(e2.getName())):num ;return num2;}});//遍历for(Employee e:ls){System.out.println(e.getName()+"---"+e.getAge());}}
}

Map的实现类

–Map:双列数据,存储key-value对的数据
—HashMap:作为Map的主要实现类,线程不安全的,效率高;存储null的key和value
----LinkedHashMap:保证在遍历map元素时,可以按照添加的顺序实现遍历。
原因:在原有的HashMap底层结构基础上,添加了一对指针,指向前一个和后一个元素
对于频繁的遍历操作,此类执行效率高于HashMap
—TreeMap:保证按照添加的key-value对进行排序,实现排序遍历。此时考虑key的自然排序和定制排序
底层使用的是红黑树
—Hashtable:作为古老的实现类;线程安全的,效率低;不能储存null的key和value
----Properties:来处理配置文件。key和value都是String类型
HashMap的底层:数组+链表 (jdk7之前)
数组+链表+红黑树 (jdk8)

Map结构的理解:

Map中的key:无序的、不可重复的,使用Set存储所有的key —>key所在的类要重写equals()和hashCode()(以hashmap为例)
Map中的value:无序的、可重复的,使用Collection存储所有的value —>value所在的类要重写equals()
一个键值对:key-value构成了一个Entry对象
Map中的entry:无序的、不可重复的,使用Set存储所有的entry