常用类

1 object类

1 API

如何阅读API文档?
1.来自于哪个包下
2.观察类的层次结构
3.观察该类是普通类还是抽象类或者是接口
普通类
	看构造方法
抽象类
	1.看它的子类
	2.看是否在方法中有静态方法返回该类的对象
接口
	1.看实现类
4.观察该类的继承了哪些类,实现了哪些接口
5.自己根据需求查找构造方法/类变量/类方法/成员方法

2 Object

Class Object是类Object结构的根。 每个班都有Object作为超类。 所有对象(包括数组)都实现了这个类的方法。 
1.任何都是用Object作为超类
2.大部分系统类都重写Object类的方法,自定义类没有实现,我们需要根据需求重写
3.任何类都直接或者间接访问了Object类的无参构造方法,同时加载了Object类的静态代码块
4.该类的设计也满足万事万物皆对象的设计原则

int hashCode() (重点掌握)
Class<?> getClass()  (反射)该方法返回的是字节码文件对象
boolean equals(Object obj) (重点掌握)
String toString() (重点掌握)
protected  Object clone() (了解)
protected  void finalize() (面试题会考,了解)
当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。用于垃圾回收,但是什么时候回收不确定。

3 int hashCode() (重点掌握)

Object定义的hashCode方法确实为不同对象返回不同的整数。 
(这通常通过将对象的内部地址转换为整数来实现,但Java的编程语言不需要此实现技术。) 

 native关键字可以和abstract共存吗? -- 不可以

  1.该方法返回的是一个和地址有关的整数值,可以理解为地址,但是不是地址
 2.有可能两个对象的hashCode一样,但是两个对象不是同一个对象
 3.如果两个对象地址一样,肯定是同一个对象
 4.hashCode方法只能够保证对象尽量唯一
public class ObjectDemo02 {
   public static void main(String[] args) {
   	Student s1 = new Student("隔壁老王", 30);
   	Student s2 = new Student("隔壁老邓", 31);
   	
   	int h1 = s1.hashCode();
   	int h2 = s2.hashCode();
   	System.out.println(h1); // 2018699554
   	System.out.println(h2); // 1311053135
   	
   	System.out.println(h1 == h2);
   }	
}

4 String toString() (重点掌握)

	注意:
     1.直接输出一个对象,默认输出的就是该对象的toString方法
     2.返回一个对象的地址+类路径毫无意义,父类Object的toString方法不能够满足子类Student的需求,所以需要方法重写
     3 格式
      @Override
      public String toString() {
    	return "我是" + name + ",我今年" + age;
 	}
 	
     一般自动生成 alt + shift + s 再按S
public class ObjectDemo04 {
	public static void main(String[] args) {
		Student s1 = new Student("隔壁老王", 30);
		Student s2 = new Student("隔壁老邓", 31);
		
//		String str1 = s1.toString();
//		String str2 = s2.toString();
//		System.out.println(s1.hashCode());
//		System.out.println(str1); // com.sxt.objectdemo.Student@7852e922
//		System.out.println(str2);
		System.out.println(s1);
		System.out.println(s2);
		
	}
}

5 boolean equals(Object obj) (重点掌握)

== 和 equals 
1 == 
比较基本数据类型
	比较的是数值本身
比较引用数据类型
	比较的是地址
	
2 equals
 不能够比较基本数据类型
 比较引用类型
 	如果你没有重写equals方法,默认比较的都是地址
 	
3. 一般自动生成  alt + shift + s再按H
   	String类的equals方法
   	"abcd".equals("abce")
   	class String {
   		private final char value[] = {'a', 'b', 'c', 'd'};
   	
   		public boolean equals(Object anObject) {
   			// "abcd" == "abce";  "abcd"
   			// 提高了程序的效率
	        if (this == anObject) {
	            return true;
	        }
	        // 提高了安全性
	        if (anObject instanceof String) {
	            String anotherString = (String)anObject;
	            int n = this.value.length; // 4
	            if (n == anotherString.value.length) {
	                char v1[] = value; {'a', 'b', 'c', 'd'}
	                char v2[] = anotherString.value; {'a', 'b', 'c', 'e'}
	                int i = 0;
	                while (n-- != 0) {
	                    if (v1[i] != v2[i])
	                        return false;
	                    i++;
	                }
	                return true;
	            }
	        }
	        return false;
	    }
   	}
   	
   	equals方法比较成员是否相等要看需求
 */
public class ObjectDemo05 {
	public static void main(String[] args) {
		Student s1 = new Student("隔壁老王", 30);
		Student s2 = new Student("隔壁老邓", 31);
		Student s3 = new Student("隔壁老邓", 31);
		
		System.out.println(s1.equals(s1)); // false
		System.out.println(s2.equals(s3)); // true
		
//		System.out.println("abcd".equals("abce"));
	}
}

6 protected Object clone() (了解)

java.lang.CloneNotSupportedException
异常名称: 克隆不支持异常

克隆出来的对象和本体一样,但是是一个独立体,和地址传递有区别

深克隆和浅克隆 【设计模式中原型模式有这个】
public class ObjectDemo06 {
	public static void main(String[] args) throws CloneNotSupportedException {
//		ArithmeticException
//		NullPointerException
//		ClassCastException
//		ArrayIndexOutOfBoundsException
		
		Student s1 = new Student("隔壁老王", 30);
		Student s2 = new Student("隔壁老邓", 31);
		
		Student s3 = (Student) s1.clone();
//		System.out.println(s3);
		
		Student s4 = s1;
		
		s3.setName("黄飞鸿");
		s3.setAge(40);
		
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s3);
		System.out.println(s4);
		
		System.out.println("====================");
		s4.setName("霍元甲");
		s4.setAge(50);
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s3);
		System.out.println(s4);
	}
}

7 protected void finalize()

当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。用于垃圾回   收,但是什么时候回收不确定。
垃圾回收期不确定性和随机性
public class ObjectDemo07 {
	public static void main(String[] args) throws Throwable {
		Student s1 = new Student("隔壁老王", 30);
//		s1.finalize();
		// 启动垃圾回收器
		System.gc();
		// 让垃圾回收器执行finalize方法,也不一定执行
		System.runFinalization();
	}
}

2 String

1 String本质就是字符数组

特点:
1.String是一个final修饰的类,不能够被继承
2.类似"abc"这样的字符串字面值常量也是String类的对象,既然是对象,就可访问String的成员
3.它们的值在创建后不能被更改,但是可以被共享
4.字符串缓冲区支持可变字符串 【StringBuffer/StringBuilder】
5.如果字符串的拼接操作非常频繁,那么String的效率不高,会在常量池创建大量的字符串,所以建议 使用字符串缓冲区
public class StringDemo01 {
	public static void main(String[] args) {
		String s = "好好学习";
		s += "天天向上";
		System.out.println("s:" + s); // s:好好学习天天向上
		/*
		 * 编译之后的结果
		 * public static void main(String args[])
			{
				String s = "好好学习";
				s = (new StringBuilder(String.valueOf(s))).append("天天向上").toString();
				System.out.println((new StringBuilder("s:")).append(s).toString());
			}
		 */
	}
}

2 string构造方法

package com.sxt.stringdemo;

import java.io.UnsupportedEncodingException;

/*  
**public String()//無參
	public String(String original)//有參
	
	public String(char[] value)//将字符数组转换成字符串
	
	public String(char[] value, int offset, int count)// 将字符数组的一部分转换成字符串
	
	public String(byte[] bytes)//将字节数组转换成字符串
	
	public String(byte[] bytes, int offset, int length) //将字节数组的一部分转换成字符串
	
	String(byte[] bytes, String charsetName) // 使用编码处理字符串 后面讲解IO流的时候讲解**
*/
public class ClassDemo02 {
	public static void main(String[] args) throws UnsupportedEncodingException {
		//public String()
		String s1 = new String();
		System.out.println("s1:"+s1);  //s1:
		
		//public String(String original)
		String s2 = new String("abc");
		System.out.println("s2:"+s2);   //s2:abc
		
		//public String(char[] value)//将字符数组转换成字符串
		char[] value = {'a','b','c'};
		String s3 = new String(value);
		System.out.println("s3:"+s3);   // s3:abc
		
		//public String(char[] value, int offset, int count)
		// 将字符数组的一部分转换成字符串
		String s4 = new String(value,1,2);
		System.out.println("s4:"+s4);   //s4:bc
		
		//public String(byte[] bytes)//将字节数组转换成字符串
		String s5 = new String(new byte[] {97,98,99,100});
		System.out.println("s5:"+s5);     //s5:abcd
		
		//public String(byte[] bytes, int offset, int length) 
		//将字节数组的一部分转换成字符串
		String s6 = new String(new byte[] {97,98,99,100},1,2);
		System.out.println("s6:"+s6);   //s6:bc
	
		//String(byte[] bytes, String charsetName) 
		// 使用编码处理字符串 后面讲解IO流的时候讲解
		String s7 = new String("張三".getBytes(),"gbk");
		System.out.println("s7"+s7);   //s7張三
	}
}

s1:
s2:abc
s3:abc
s4:bc
s5:abcd
s6:bc
s7張三

3 字符串常用方法

1

package com.sxt.class02;

/*
  **char charAt(int index) //根据索引找某一个字符
  	
	int indexOf(int ch) //某个字符的索引
	
	int indexOf(String str) //某个字符串首个字母的索引
	
	int indexOf(int ch,int fromIndex) //从fromIndex索引开始从左往右找第一次出现ch/str的字符或者字符串的索引
	int indexOf(String str,int fromIndex)
	
	int lastIndexOf(int ch) //从右往左找第一次出现字符ch所对应的索引  
	
	int lastIndexOf(int ch,int fromIndex)  
	int lastIndexOf(String str,int fromIndex)//从fromIndex索引开始从右往左找第一次出现ch/str的字符或者字符串的索引 
	
	String substring(int start)//从start开始截取到末尾
	String substring(int start,int end)//截取一部分,左闭右开原则
	int length()  
	注意: length,length(),size()的区别**
*/
public class ClassDemo05 {
	public static void main(String[] args) {
		String s = "HelloWorld";
		
		//char charAt(int index) //根据索引找某一个字符
		System.out.println("charAt:"+ s.charAt(0)); //charAt:H
		//遍历这个字符串
		for (int i = 0; i < s.length(); i++) {
			System.out.println(s.charAt(i));  //H   e   l   l   o   W   o   r   l   d
		}
		System.out.println();
		
		//int indexOf(int ch) //某个字符的索引
		System.out.println(s.indexOf('e'));// 1
		
		//int indexOf(String str) 
		System.out.println(s.indexOf("World"));  //5
		
		 // int indexOf(int ch,int fromIndex) 
		 //int indexOf(String str,int fromIndex) 
		//从fromIndex索引开始从左往右找第一次出现ch/str的字符或者字符串的索引
		System.out.println(s.indexOf('o',5));  //6
		System.out.println(s.indexOf("ll",1));  //2
		
		//int lastIndexOf(int ch) 从右往左找第一次出现字符ch所对应的索引
		System.out.println(s.lastIndexOf('l'));  //8
		
		//int lastIndexOf(int ch,int fromIndex)  
		//int lastIndexOf(String str,int fromIndex)  
		//从fromIndex索引开始从右往一次出现ch/str的字符或者字符串的索引
		System.out.println(s.lastIndexOf('l',9)); //8
	
		//String substring(int start) 从start开始截取到末尾
		System.out.println(s.substring(s.indexOf('W')));  //word
		//String substring(int start,int end) 左闭右开原则
		System.out.println(s.substring(5, 7)); //wo
	}
}
charAt:H
H   e   l   l   o   W   o   r   l   d

1
5
6
2
8
8
World
Wo

2

package com.sxt.stringdemo;

/*   
    boolean isEmpty():判断字符串是否为空。
    
	boolean equals(Object obj):将此字符串的内容与指定的对象比较,区分大小写。
	
	boolean equalsIgnoreCase(String str):将此 String 与另一个 String 比较,
	忽略大小写。
	
	boolean contains(String str):判断字符串中是否包含方法传入的字符串。
	
	boolean startsWith(String str):判断字符串是否以某个指定的字符串开头。
	
	boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾。
 */
public class StringDemo05 {
	public static void main(String[] args) {
		String s1 = "HelloWorld";
		System.out.println("isEmpty:" + s1.isEmpty()); // false
		
		String s = "";
		String sss = null;  //null不能调用方法,编译报错
		String ss = new String();
		
		System.out.println("isEmpty:" + s.isEmpty()); // true
		System.out.println("isEmpty:" + ss.isEmpty()); // true
		//System.out.println("isEmpty:" + sss.isEmpty()); // 报错
		
		//boolean equalsIgnoreCase(String str)
		System.out.println(s1.equalsIgnoreCase("Helloworld"));
		
		//boolean contains(String str)  
		System.out.println("contains:" + s1.contains("World2"));
		
		//boolean startsWith(String str)
		System.out.println("http://www.baidu.com".startsWith("http://"));
		
		//boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾。
		System.out.println("HelloWorld.java".endsWith(".java"));
		
		System.out.println("Hello".contains(""));
		System.out.println("http://www.baidu.com".startsWith(""));
		System.out.println("HelloWorld.java".endsWith(""));
		
		//字符要变成字符串怎么做
		char ch = 'a';
		String s2 = ch + "";
		System.out.println(s2);
		
		//HelloWorld = "" + H + "" + e + "" + L	
	}
}

3

package com.sxt.stringdemo;

import java.util.Arrays;

import com.sxt.objectdemo.Student;

/*
    byte[] getBytes() :将字符串转化为字节数组。此方法也是编码的过程
  
	char[] toCharArray(): 将字符串转化为字符数组。
	
	static String valueOf(char[] chs): 返回 char 数组参数的字符串表示形式。
	
	static String valueOf(int i) :返回 int 参数的字符串表示形式。
	
	String toLowerCase() :将此 String 中的所有字符都转换为小写。
	
	String toUpperCase() :将此 String 中的所有字符都转换为大写。
	
	String concat(String str): 将指定字符串连接到此字符串的结尾。
	
	今	晚	打	老	虎	
	25	46	18	75	62
	11010101010101010101010101
	
	码表: GBK UTF-8 ISO-8859-1
 */
public class StringDemo06 {
	public static void main(String[] args) {
//		byte[] getBytes() :将字符串转化为字节数组。此方法也是编码的过程
		String s = "HeyMan";
		byte[] bys = s.getBytes();
		System.out.println(Arrays.toString(bys));
		
//		char[] toCharArray(): 将字符串转化为字符数组。
		char[] chs = s.toCharArray();
		System.out.println(Arrays.toString(chs));
		
		/*
		 *  valueOf表示将任意类型转换成字符串
		 *  static String valueOf(char[] chs): 返回 char 数组参数的字符串表示形式。
		 *  static String valueOf(int i) :返回 int 参数的字符串表示形式。
		 */
		String s2 = String.valueOf(false);
		String s3 = String.valueOf(new Student("张三", 18));
		System.out.println(s2);
		System.out.println(s3);
		
//		String toLowerCase() :将此 String 中的所有字符都转换为小写。
		System.out.println("G".toLowerCase());
//		String toUpperCase() :将此 String 中的所有字符都转换为大写。
		System.out.println("t".toUpperCase()); 
//		String concat(String str): 将指定字符串连接到此字符串的结尾。
		System.out.println("Hello".concat("World"));
	}
}

4

package com.sxt.stringdemo;

/*
    String replace(char old,char new) :替换功能。
    
	String replace(String old,String new) :替换功能。
	
	String trim():去除字符串两空格。
	
	int compareTo(String str) :按字典顺序比较两个字符串。
	
	int compareToIgnoreCase(String str):按字典顺序比较两个字符串,忽略大小写。
	
	public String[] split(String regex):分隔字符串成字符数组。
 */
public class StringDemo07 {
	public static void main(String[] args) {
		String s = "Hello*WorldJava";
		System.out.println(s.replace('*', '_'));
		System.out.println(s.replace("Java", "Android"));
//		String trim():去除字符串两空格。
		String s2 = "   123456   7899   ";
		System.out.println(s2.trim() + "=========");
//		int compareTo(String str) :按字典顺序比较两个字符串。
		String s3 = "HelloWorld";
		System.out.println(s3.compareTo("HElloWorld"));
//		public String[] split(String regex):分隔字符串成字符数组。
		String s4 = "Hello123World25Man";
		String[] strs = s4.split("\\d");
		for (String ss : strs) {
			System.out.println(ss);
		}
	}
}

4 StringBuffer和StringBuilder

1 StringBuffer

1 作用

之前String类,每次拼接一个字符串,系统都为之开辟一个新的内存空间,这样既耗时又占用了大量  的空间,
StringBuffer就可以处理这个问题,它是一个字符串缓冲区。

2 StringBuffer类概述

线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。虽然在任意 时间点上它都包含某种定的字符序列
但通过某些方法调用可以改变该序列的长度和内容。

3 特点:

1.可变长的字符序列
2.线程安全,效率低  StringBuffer
	线程(工作线程)
		
		安全性
		效率
	二者只能取其中一个

	买票取钱 安全   StringBuffer
    访问网站 效率  StringBuilder

4 StringBuffer和StringBuilder构造方法

StringBuffer() 
构造一个没有字符的字符串缓冲区,初始容量为16个字符。  

StringBuffer(CharSequence seq) 
构造一个包含与指定的相同字符的字符串缓冲区 CharSequence 。  

StringBuffer(int capacity) 
构造一个没有字符的字符串缓冲区和指定的初始容量。  

StringBuffer(String str) 
构造一个初始化为指定字符串内容的字符串缓冲区。 
public class StringBufferDemo01 {
	public static void main(String[] args) {
		// 创建了一个字符串容器
		StringBuilder sb = new StringBuilder();
		System.out.println("sb:" + sb);
		System.out.println("capcity: " + sb.capacity()); // 16
		System.out.println("length: " + sb.length()); // 0
		
		StringBuffer sb2 = new StringBuffer("abc");
		System.out.println("capcity: " + sb2.capacity()); // 19
		System.out.println("length: " + sb2.length()); // 3
		
		// StringBuffer(int capacity) 
		StringBuffer sb3 = new StringBuffer(30);
		System.out.println("capcity: " + sb3.capacity()); // 30
		System.out.println("length: " + sb3.length()); // 0
		
	}
}

2 StringBuffer和StringBuilder增删查改

增 :
	StringBuffer append(String str) 
	StringBuffer insert(int offset, String str)
	
删 :
	StringBuffer deleteCharAt(int index) 
	StringBuffer delete(int start, int end)
	 
改:
	public StringBuffer replace(int start,int end,String str)

其他:
	public StringBuffer reverse() 
	public String substring(int start)
	public String substring(int start,int end)
public class StringBufferDemo02 {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		StringBuffer sb2 = sb.append("hello");
//		StringBuffer append(String str) 
		System.out.println("sb: " + sb); // sb: hello
		System.out.println("sb2: " + sb2); // sb2: hello
		
		sb.append("world").append(10).append(new Student("老王", 35));
		System.out.println(sb);
		
//		StringBuffer insert(int offset, String str)
		sb.insert(sb.toString().indexOf("1"), "老邓");
		System.out.println(sb);
		
//		StringBuffer deleteCharAt(int index) 
		sb.deleteCharAt(sb.indexOf("1"));
		System.out.println(sb);
		
//		StringBuffer delete(int start, int end) 
		sb.delete(sb.indexOf("S"), sb.length());
		System.out.println(sb);
		
//		public StringBuffer replace(int start,int end,String str)
		sb.replace(sb.indexOf("老"), sb.indexOf("0"), "Java");
		System.out.println(sb);
		
		/*
		 *  public StringBuffer reverse() 
		 *	public String substring(int start)
		 *	public String substring(int start,int end)
		 */
		sb.reverse();
		System.out.println(sb);
		sb.reverse();
		
//		public String substring(int start)
		String result = sb.substring(sb.indexOf("0"));
		System.out.println(sb);
		System.out.println(result);
		
		CharSequence cs = sb.subSequence(sb.indexOf("w"), sb.indexOf("J"));
		System.out.println(cs);
		
	}
}

3 String和StringBuffer和StringBuilder区别

1 StringBuffer类

三者本质都是字符序列

线程安全,同步,效率低	StringBuffer
线程不安全,不同步,效率高 StringBuilder
举例:
    1.买票  安全
    2.访问网站 发送请求请求 index.html 效率

三者的区别 String StringBuffer StringBuilder
二者是完全兼容的,二者都是字符串缓冲区,支持可变的字符串操作
线程安全,同步,效率低	StringBuffer

线程不安全,不同步,效率高 StringBuilder

2 StringBuilder

一个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。线程不安全,效率高
该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。
如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。 用法完全和StringBuffer一样。

3 String 长度不可变,线程不安全,效率高

1.String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。 
2.字符串是常量;它们的值在创建之后不能更改。
3.所有的常量在内存的方法区的常量池中
4.频繁的字符串拼接操作会导致常量池容器增加,浪费内存资源
5.字符串缓冲区【StringBuffer,StringBuilder】支持可变的字符串
6.Java在编译时期会针对字符串的拼接操作使用StringBuilder改进,提高效率,节约内存资源
	s = (new StringBuilder(String.valueOf(s))).append("efg").toString();
	System.out.println((new StringBuilder("s:")).append(s).toString());
7.因为 String 对象是不可变的,所以可以共享
8.字符串本质是字符数组

5 正则表达式

1 概念:

使用单个字符串来描述/匹配一系列符合某个语法规则的字符串

在Java里面来学习正则表达式的目的主要就是使用正则表达式来处理字符串复杂的查找 find/替换replace/匹配matches/分割split工作

使用步骤
1.通过大量的字符串找规律定义规则
2.使用这种规则去匹配新的字符串
3.匹配成功作出相应的操作(匹配 查找 替换 分割) 

正则表达式由两种基本字符组成
 原义字符:字符本身就是一个正则表达式,例如 a, b, c ,\t ,\n ,\r ,\f等等 
 元字符: * + ? $ ^ () [] {}等等
 
 字符类:  [abc] 将字符进行归类,可以出现[]中的其中一个 对abc其中一个进行匹配
 		[^abc] 对不是abc的字符进行匹配
范围类:
	[a-z] 表示代表a-z中的一个字符
	表示所有的英文字母和数字 [a-zA-Z0-9]
	中文的正则表达式范围 [\u4e00-\u9fa5]

预定义类:
	\d == [0-9] 数字
	 
	\D == [^0-9] 非数字
	 
	空白字符:[ \t\n\x0B\f\r] == \s
	 
	[^ \t\n\x0B\f\r] == \S
	[a-zA-Z0-9_] \w
	[^a-zA-Z0-9] \W
	. 任何字符(与行结束符可能匹配也可能不匹配) 

边界字符
	^:以XXX开头 
	例如以a开头 ^a
	$:以XXX结尾
	例如以b结尾 b$
	\b:单词边界
	\B:非单词边界

量词
	?:出现0次或者1次  
	a?
	+:出现1次或者多次
	a+
	*:出现任意次
	a*
	{n}:出现正好n次
	a{4}
	{n,m}出现n-m次
	a{2,6}
	{n,}出现至少n次
	a{3,}
	 
分组 ()
如何让Jack出现至少3次,而不是k出现三次
错误写法 Jack{3,}
使用分组的正确写法: (Jack){3,}
(Jack){3,}(?:love){2,}(work){3,}
	 
忽略分组:每一组能够分组,但是没有编号 ?:

或 |
Ja(ck|Love)Kitty

反向引用
利用分组的编号进行反向引用
反向引用使用$,必须先分组

将日期2018-04-27 转换成为 04/27/2018
public class RegexDemo02 {
	public static void main(String[] args) {
		String s = "http://abc aaa 123 . _haha	哈哈 [yz.java";
		System.out.println("原字符串: " + s);
		
		System.out.println(s.replaceAll("a", "X"));
		System.out.println(s.replaceAll("[abc]", "X"));
		System.out.println(s.replaceAll("[^abc]", "X"));
		System.out.println(s.replaceAll("[a-z]", "X"));
		System.out.println(s.replaceAll("[a-z]", "X"));
		System.out.println(s.replaceAll("[a-zA-Z0-9]", "X"));
		System.out.println(s.replaceAll("[\\u4e00-\\u9fa5]", "X"));
		System.out.println(s.replaceAll("[\\d]", "X"));
		System.out.println(s.replaceAll("[\\s]", "X"));
		System.out.println(s.replaceAll("[\\S]", "X"));
		System.out.println(s.replaceAll("[\\w]", "X"));
		System.out.println(s.replaceAll(".", "X"));
		System.out.println(s.replaceAll("\\.", "X"));
		System.out.println(s.replaceAll("^(http://)", "X"));
		System.out.println(s.replaceAll("(.java)$", "X"));
		System.out.println(s.replaceAll("\\b", "X"));
		System.out.println(s.replaceAll("\\B", "X"));
		
		//将日期2018-04-27 转换成为 04/27/2018( 反向引用 )
		String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
		String ss = "2018-04-27";
		System.out.println("原日期字符串:" + ss);
		String replace = ss.replaceAll(regex, "$2/$3/$1");
		System.out.println("使用正则修改后的日期字符串:" + replace);
		}
}

2正则表达式的优点

package com.sxt.regexdemo;

import java.util.Scanner;

/*
 * 需求:假设我们要对QQ号做验证,验证的规则是:
		1.qq号必须是5-10位
		2.数字0不可以作为qq号码的开头
		3.qq号码肯定是数字
		
 */
public class RegexDemo01 {
	public static void main(String[] args) {
		System.out.println("请输入QQ号码:");
//		System.out.println(checkQQ(new Scanner(System.in).next()));
		System.out.println(checkQQByRegex(new Scanner(System.in).next()));
	}
	
	public static boolean checkQQ(String qq) {
		boolean flag = true;
		
		// 1.qq号必须是5-10位
		if (qq.length() >= 5 && qq.length() <= 10) {
			// 2.数字0不可以作为qq号码的开头
			if (!qq.startsWith("0")) {
				char[] chs = qq.toCharArray();
				for (char c : chs) {
					// 3.qq号码肯定是数字
					if (!(c >= '0' && c <= '9')) {
						flag = false;
						break;
					}
				}
			} else {
				flag = false;
			}
		} else {
			flag = false;
		}
		
		return flag;
	}
	
	// 使用正则表达式之后
	public static boolean checkQQByRegex(String qq) {
		return qq.matches("[1-9]\\d{4,9}");
	}
}

2 正则表达式在Java中的应用

在Java里面来学习正则表达式的目的主要就是使用正则表达式来处理字符串复杂的
1.字符串查找操作 find , Pattern 和 Matcher
2.字符串匹配操作 字符串的matches()方法 完全匹配
3.字符串替换操作 字符串的replaceAll()和replaceFirst()方法 ,全文检索,满足条件即可替换
4.字符串分割 split()方法

public class RegexDemo03 {
	public static void main(String[] args) {
		String s = "xxyz.123";
		String regex = "x{2}yz\\.\\d{3}";
		// 匹配
		System.out.println(s.matches(regex));
		
		// 替换 
		/*
		 * 先对整个源字符串进行查找
		 * 匹配成功,就直接替换
		 * 匹配失败,不做任何处理
		 */
		regex = "[x\\d]";
		System.out.println(s.replaceFirst(regex, "*"));
		System.out.println(s.replaceAll(regex, "*"));
		
		/*
		 * split
		 * 先对整个源字符串进行查找
		 * 匹配成功,就直接分割
		 * 匹配失败,不做任何处理
		 */
		regex = "\\.";
		System.out.println(Arrays.toString(s.split(regex)));
	}
}

3 字符串查找操作 Pattern和Matcher ?

Java是面向对象语言 正则表达式本身也应该理解为一个对象,这个对象Java提供了就叫做 Pattern
Matcher它就是匹配器对象
如果需要匹配一个字符串是否满足正则条件需要哪些材料?
1.源字符串 s
2.需要正则表达式对象 Pattern

public class RegexDemo07 {
   public static void main(String[] args) {
   	// 原生写法
   	String regex = "x?yz";
   	String s = "xyz";
   	boolean matches = s.matches(regex);
   	System.out.println(matches);
   	
   	// Pattern和Matcher写法
   	// 1.创建正则表达式对象( 将正则表达式字符串封装成为正则表达式对象)
   	Pattern p = Pattern.compile("x?yz");
   	// 2.创建匹配器(通过正则表达式对象创建对应的匹配器对象)
   	Matcher m = p.matcher(s);
   	// 3.使用匹配器( 通过匹配器匹配,匹配成功可以有更多方法来操作字符串)
   	boolean matches2 = m.matches();
   	System.out.println(matches2);
   }
}

6 包装类

1 为什么需要学习包装类?

1、如何判断一个字符是大写,小写还是数字字符?
	c >= 'a' && c <= 'z'
	该判断是与字符相关,应该放在字符类里面  Character  char
2、如何计算65的二进制,八进制,十六进制呢? -- 那么27进制
	该计算与整数有关,应该放在整数类里面 Integer Byte Short Long

有了包装类,我们就可以访问和数据类型相关的对象的更多的方法
基本数据类型是没有方法可以调用的

3 ,何的数据类型都有一个class属性,它返回的是类文件
4 ,什么是包装类?
八大基本数据类型都对应着一个包装类类型
byte short int long float double char boolean
Byte Short Integer Long Float Double Character Boolean

掌握 Integer 和 Character,其他的一模一样
Integer是java.lang.Number 包下面的
任何 Number类下的子类都可以转换成其他的数值类型,但是可能会出现精度丢失

static int BYTES
用于表示二进制补码二进制形式的 int值的字节数。
static int MAX_VALUE
一个持有最大值一个 int可以有2 31 -1。
static int MIN_VALUE
的常量保持的最小值的 int可以具有,-2 31。
static int SIZE
用于表示二进制补码二进制形式的 int值的位数。
static 类 TYPE
类原始类型 int的 类实例。

Integer(int value) 
构造一个新分配的 Integer对象,该对象表示指定的 int值。  
Integer(String s) 
构造一个新分配 Integer对象,表示 int由指示值 String参数。  
NumberFormatException
异常名称: 数字格式化异常
产生原因: 字符串未满足数字的格式

2包装类成员方法

 public int intValue()  拆箱,将Integer转化为整型
 public static int parseInt(String s)  将字符串转换为int类型
 public static String toString(int i)  将整型转换为字符串
 public static Integer valueOf(int i)  将整型装换为Integer类型
 public static Integer valueOf(String s)  将字符串转换为Integer类型
 
 new Integer和Integer.valueOf()区别?
 看源码:
 public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
public class IntegerDemo02 {
	public static void main(String[] args) {
		Integer ii = new Integer(100);
		byte byteValue = ii.byteValue();
		short shortValue = ii.shortValue();
		int intValue = ii.intValue();
		long longValue = ii.longValue();
		float floatValue = ii.floatValue();
		double doubleValue = ii.doubleValue();
		System.out.println(byteValue);
		System.out.println(shortValue);
		System.out.println(intValue);
		System.out.println(longValue);
		System.out.println(floatValue);
		System.out.println(doubleValue);
		
		int i = Integer.parseInt("200");
		System.out.println(i);
		
		String s = Integer.toString(20);
		System.out.println(s);
		
		Integer ii2 = Integer.valueOf(100);
		System.out.println(ii2);
		
		Integer ii3 = Integer.valueOf("500");
		System.out.println(ii3);
	}
}

3实现String和int之间的相互转换

parse 解析 将字符串中的数据提取出来存储对应的实体类中
1.日期解析
2.xml解析
3.json解析
4.html解析

format 格式化
将实体类中的数据转换成字符串

public class IntegerDemo03 {
	public static void main(String[] args) {
		// int -> String
		// 方式一:
		int i = 10;
		String s = i + ""; // new StringBuilder().append(i);
		
		// 方法二:
		String s2 = String.valueOf(i); // 常用
		
		// 方式三:
		String s3 = Integer.valueOf(i).toString();
		
		// String --> int
		// 方式一:
		String str = "100";
		int ii = Integer.parseInt(str); // 最常用
		
		// 方式二:
		int ii2 = new Integer(str).intValue();
		
		// 方式三:
		int ii3 = Integer.valueOf(str).intValue();
		
	}
}

4 自动拆装箱和自动装箱

自动拆装箱: 保证基本数据类型和包装类类型之间相互运算

自动拆箱:自动将包装类类型转换成基本数据类型,本质依赖的方法 ii.intValue()
自动装箱:自动将基本数据类型转换成包装类类型,本质依赖的方法 Integer.valueOf(100)

public class IntegerDemo04 {
	public static void main(String[] args) {
	   // 装箱: 将基本数据类型转换成对应的包装类类型
	   Integer ii = new Integer(100);
	   // 拆箱: 将包装类类型转换成对应的基本数据类型
	   int i = ii.intValue();
	   
	   // 自动装箱
	   Integer ii2 = 100; //Integer ii2 = Integer.valueOf(100)
	   ii2 += 20; // ii = ii + 20;ii2 = Integer.valueOf(ii.intValue() + 20);
	
//	   Integer iii = null;
//	   iii += 100;
//	   System.out.println(iii);
	   
	   int x = ii2 + 5;
	   boolean bool = ii2 > 5;
	}
}

class Student {
	private String name;
	private Integer age;
	private Double height;
}

5 Integer类实现进制转换

1 进制转换的分类:

1.其他进制->十进制  按权展开
2.十进制->其他进制 取余法
3.X进制->Y进制 先将X进制转换成十进制,再将十进制转换成Y进制

快速转换法
4.二进制,八进制,十六进制快速转换法  分组法
5.十进制和二进制的快速转换法  8421码

2 计算只会两种方式

	1.其他进制->十进制  按权展开
	2.十进制->其他进制 取余法

3 十进制到其他进制

public static String toBinaryString(int i)
public static String toOctalString(int i)
public static String toHexString(int i)
public static String toString(int i,int radix)
其他进制到十进制
public static int parseInt(String s,int radix)	

计算机只能够表示到36进制
public class IntegerDemo05 {
	public static void main(String[] args) {
		System.out.println(Integer.toBinaryString(100));
		System.out.println(Integer.toOctalString(100));
		System.out.println(Integer.toHexString(100));
		System.out.println(Integer.toString(100));
		
		System.out.println(Integer.toString(100, 36)); // 2s
		
		System.out.println(Integer.parseInt("100101", 2));
		System.out.println(Integer.parseInt("7", 8));
		System.out.println(Integer.parseInt("a", 16));
		System.out.println(Integer.parseInt("z", 36));
		
		System.out.println(getNum(16, 2, "ff"));
	}
	
	// 书写一个方法实现任意进制的转换
	public static int getNum(int xRadix, int yRadix, int num) {
		// 将X进制的num转换成十进制
		int i = Integer.parseInt(String.valueOf(num), xRadix);
		// 将十进制的i转换成对应Y进制
		String s = Integer.toString(i, yRadix);
		return Integer.parseInt(s);
	}
	
	public static String getNum(int xRadix, int yRadix, String num) {
		// 将X进制的num转换成十进制
		int i = Integer.parseInt(num, xRadix);
		// 将十进制的i转换成对应Y进制
		String s = Integer.toString(i, yRadix);
		return s;
	}
}

6对于超出int范围内的数据进行运算(BigInteger)

1构造方法

   public BigInteger(String val)

2成员方法

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)	
public class BigIntegerDemo01 {
	public static void main(String[] args) {
//		int i = Integer.MAX_VALUE;
//		System.out.println(i + 1);
		
		System.out.println(new BigInteger("2147483647").add(new BigInteger("1")));
		System.out.println(new BigInteger("2147483647").subtract(new BigInteger("1")));
		System.out.println(new BigInteger("2147483647").multiply(new BigInteger("10")));
		System.out.println(new BigInteger("2147483647").divide(new BigInteger("10")));
		
		BigInteger remainder = new BigInteger("4").remainder(new BigInteger("2"));
		System.out.println(remainder);
		System.out.println(Arrays.toString(new BigInteger("4").divideAndRemainder(new BigInteger("2"))));
	}
}

7 Character及其他包装类

1 Character类概述:

Character类概述: Character类是char的包装类。
char对应的包装类 Character

2 构造方法

public Character(char value)

3成员方法

public static boolean isUpperCase(char ch)  判断字符是否是大写
public static boolean isLowerCase(char ch)  判断字符是否是小写
public static boolean isDigit(char ch)  判断字符是否是数字
public static char toUpperCase(char ch)  将字符转大写
public static char toLowerCase(char ch)  将字符转小写 
public class CharacterDemo {
	public static void main(String[] args) {
		Character ch = new Character('a');
//		Character character = 'a';
		
		System.out.println(Character.BYTES);
		System.out.println((int)Character.MAX_VALUE);
		System.out.println(Character.MAX_RADIX);
		System.out.println(Character.MIN_VALUE);
		System.out.println(Character.SIZE);
		
		System.out.println(Character.isUpperCase('A')); 
		System.out.println(Character.isLowerCase('a'));
		System.out.println(Character.isDigit('0'));
		System.out.println(Character.toUpperCase('a'));
		System.out.println(Character.toLowerCase('A'));
		
		System.out.println(Character.isJavaIdentifierPart('1'));
		
	}
}

4 byte short int long float double 的包装类都是Number类的子类

public class OtherPackageClassDemo {
	public static void main(String[] args) {
		byte by = 30;
		Byte byt = new Byte(by);
		System.out.println(byt);
		
		Byte byte1 = Byte.valueOf((byte)30);
		byte byteValue = byt.byteValue();
		
		byte parseByte = Byte.parseByte("30");
		
		byt.shortValue();
		byt.intValue();
		byt.longValue();
		
		Long long1 = new Long(100L);
		long1.intValue();
		long1.floatValue();
		
		long parseLong = Long.parseLong("231311");
		Long.valueOf(1000L);
		
		Boolean boolean1 = new Boolean(false);
		boolean1.booleanValue();
		
		Boolean valueOf = Boolean.valueOf(false);
		
	}
}

8 BigDecimal

1 BigDecimal 作用

在一些金融项目当中,在进行小数运算的时,float、double很容易丢失精度为了能精确的表示、计算浮点数, Java设计了BigDecimal。

以后学习数据库的时候,数据库查询出来的数据没有整数和小数之分,
统称为 Number类型【数据库类型 Oracle】
从数据库中转换到Java对应的数据类型就是 BigDecimal类型

2 BigDecimal类概述

BigDecimal:不可变的、任意精度的有符号十进制数。

3 构造方法

public BigDecimal(String val)

4 成员变量

public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor)
public class BigDeccimalDemo {
	public static void main(String[] args) {
//		System.out.println(0.01 + 0.09);
//		System.out.println(1.0 - 0.33);
//		System.out.println(1.015 * 100);
//		System.out.println(1.301 / 100);
		
		System.out.println(new BigDecimal("0.01").add(new BigDecimal("0.09")));
		System.out.println(new BigDecimal("1.0").subtract(new BigDecimal("0.33")));
		System.out.println(new BigDecimal("1.015").multiply(new BigDecimal("100")));
		System.out.println(new BigDecimal("1.301").divide(new BigDecimal("100")));
		
	}
}

7 Date类

1 Date类概述

Date类概述:类 Date 表示特定的瞬间,精确到毫秒。 

2 构造方法

public Date()  根据当前的默认毫秒值创建日期对象
public Date(long date)  根据给定的毫秒值创建日期对象

3 成员方法

public long getTime()  获取时间,以毫秒为单位
public void setTime(long time))  设置时间	

如果需要获取年月日时分秒,建议使用Calendar

在数据库中查询出来的日期类型是 java.sql.Date类型
如何将java.sql.Date转换成java.util.Date

计算机是如何来保存时间的?
利用的就是 1970年 距离现在经过了多少个毫秒
public class DateDemo01 {
	public static void main(String[] args) {
		Date d = new Date(); // 
		System.out.println(d);// Wed Apr 24 16:31:14 CST 2019
		
//		System.out.println(d.getTime()); // 1556094674641
		
//		long currentTimeMillis = System.currentTimeMillis(); // 返回的是当前时间距离 1970经历了多少毫秒
//		System.out.println(currentTimeMillis);
		
//		Date d2 = new Date(1556094674641L);
//		System.out.println(d2);

//		将 sqlDate转换成 utilDate
		java.sql.Date sqlDate = new java.sql.Date(d.getTime());
		System.out.println(sqlDate);
		
		Date utilDate = new Date(sqlDate.getTime());
		System.out.println(utilDate);
	}
}

4 解析和格式化

格式化: 实体类 --> 字符串 format
解析: 字符串 --> 实体类 parse

public class DateFormatDemo {
	public static void main(String[] args) throws ParseException {
		Date d = new Date();
		System.out.println(d);
		
		// 2019年04月24号 16:39:25
		DateFormat df = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss");
		String dateStr = df.format(d);
		System.out.println(dateStr);
		
		String date = "2018/06/25 03点28分45秒";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH点mm分ss秒");
		Date date2 = sdf.parse(date);
		System.out.println(date2);
		
	}
}

5 Calendar

1 Calendar类概述:Calendar 类是一个抽象类,

它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,
并为操作日历字段(例如获得下星期的日期)提供了一些方法,瞬间可用毫秒值来表示。

2 成员方法

public static Calendar getInstance()
public int get(int field)
public void add(int field,int amount)
public final void set(int year,int month,int date)	

	 将日历和日期类相互转换
	Date d = new Date(c.getTimeInMillis());
	System.out.println(d);
	
	 将日期转换成日历
	Date d2 = new Date();
	c.setTimeInMillis(d2.getTime());
public class CalendarDemo01 {
	public static void main(String[] args) {
		Calendar c = Calendar.getInstance(Locale.CHINA);
		System.out.println(c);
		
//		public int get(int field)
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		System.out.format("%d年%s月%d日 %d:%d:%d%n", year, (month < 10) ? "0" + month: month, day, hour, minute, second);
		
//		long millis = c.getTimeInMillis();
//		System.out.println(millis);
		
		// 将日历和日期类相互转换
//		Date d = new Date(c.getTimeInMillis());
//		System.out.println(d);
		
		// 将日期转换成日历
//		Date d2 = new Date();
//		c.setTimeInMillis(d2.getTime());
		
//		public void add(int field,int amount)
		c.add(Calendar.YEAR, 100);
		year = c.get(Calendar.YEAR);// 2001
		System.out.format("%d年%s月%d日 %d:%d:%d%n", year, (month < 10) ? "0" + month: month, day, hour, minute, second);
		
		c.add(Calendar.MONTH, -12);
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		System.out.format("%d年%s月%d日 %d:%d:%d%n", year, (month < 10) ? "0" + month: month, day, hour, minute, second);
		
		// public final void set(int year,int month,int date)	
		c.set(1970, 8, 1);
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		System.out.format("%d年%s月%d日 %d:%d:%d%n", year, (month < 10) ? "0" + month: month, day, hour, minute, second);
		
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值