Java的IO流 Li.042

Java 的 IO 流 字节流, 字节流可以操作任何数据, 计算机中存储是字节流 InputStream OutputStream 字符流, 只能操作纯字符数据, 比较方便 Reader Writer 使用IO流要导入包, 使用时要进行异常处理, 使用后要释放资源 FileInputStream 读取一个文件 import java.io.FileInputStream; import java.io.IOException; public class Demo1_FileInputStream { public static void main(String[] args) throws IOException { FileInputStream fps = new FileInputStream("test.txt"); int x; while ((x = fps.read() ) != -1){ System.out.println(x); } fps.close(); } } read() 为什么接收的int类型 因为字节输入流可以操作任意类型的文件,比如图片音频等, 这些文件底层都是以二进制形式的存储的,如果每次读取都返回byte, 有可能在读到中间的时候遇到111111111,那么这11111111是byte类型的-1, 我们的程序是遇到-1就会停止不读了,后面的数据就读不到了,所以在读取的时候用int类型接收, 如果11111111会在其前面补上24个0凑足4个字节,那么byte类型的-1就变成int类型的255了这样可以保证整个数据读完, 而结束标记的-1就是int类型 字节输出流 write() void write(int b) throws IOException 在输出时int 去掉前3个byte字节, 写入第4个byte到文件中, 这个写是覆盖 import java.io.FileOutputStream; import java.io.IOException; public class Deom2_FileOutputStream { public static void main(String[] args) throws IOException { FileOutputStream fps = new FileOutputStream("test.txt"); fps.write(100); fps.write(101); fps.write(102); fps.close(); } } 字节输出流 追加 FileOutputStream(File file, boolean append) throws FileNotFoundException 输出字节流是否选择追加 import java.io.FileOutputStream; import java.io.IOException; public class Demo3_FileOutputStream { public static void main(String[] args) throws IOException { FileOutputStream fps = new FileOutputStream("test.txt", true); fps.write(100); fps.write(101); fps.close(); } } 复制文件 byte字节读取, byte复制 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Demo4_FileInOutStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("test.txt"); FileOutputStream fos = new FileOutputStream("copy.txt"); int b = 0; while ( (b = fis.read() )!= -1){ fos.write(b); } fis.close(); fos.close(); } } FileInputStream 的 available方法 int available() throws IOException 返回输入流的长度 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Demo5_FileInOutStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("test.txt"); FileOutputStream fos = new FileOutputStream("copy.txt"); int len = fis.available(); byte[] arr = new byte[fis.available()]; fis.read(arr); fos.write(arr); fis.close(); fos.close(); } } 通过数组 byte[] 读取写入 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Demo6_FileInOutStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("test.txt"); FileOutputStream fos = new FileOutputStream("copy.txt"); byte[] arr = new byte[1024 * 1024]; int b = 0; while ( (b =fis.read(arr)) != -1 ){ fos.write(arr,0,b); } fis.close(); fos.close(); } private static void errSimple() throws IOException { FileInputStream fis = new FileInputStream("test.txt"); FileOutputStream fos = new FileOutputStream("copy.txt"); byte[] arr = new byte[3]; int b = 0; while ( (b =fis.read(arr)) != -1 ){ fos.write(arr); } fis.close(); fos.close(); } } BufferedInputStream BufferedOutputStream 原码先读取1024*8个字节到内存, 复制给 BufferedOutputStream 1024*8 然后才写入文件 只需要关闭BufferedInputStream BufferedOutputStream 就能关闭所有流 import java.io.*; public class Demo7_BufferInputStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("test.txt"); FileOutputStream fos = new FileOutputStream("copy.txt"); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); int b ; while( ( b = bis.read() ) != -1){ bos.write(b); } // 只需关闭 BufferedInputStream BufferedOutputStream bis.close(); bos.close(); } } flush和close方法的区别 flush 刷新缓冲区, 缓冲区写到文件中, 刷完可以继续写. close 关闭前 就会刷新缓冲区 将缓冲区内容存到文件中 import java.io.*; public class Demo8_FlushClose { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("test.txt"); FileOutputStream fos = new FileOutputStream("copy.txt"); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); int b ; while ( (b = bis.read()) != -1 ){ bos.write(b); bos.flush(); } bis.close(); bos.close(); } } 字节流读取中文有乱码 UTF-8中英文1个字节, 中文3个字节, 按字节读取都会读出乱码 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class Demo9_CharIO { public static void main(String[] args) throws IOException { // Demo1(); FileOutputStream fos = new FileOutputStream("chinese.txt"); fos.write("你好啊, 世界!".getBytes(StandardCharsets.UTF_8)); fos.write("\r".getBytes(StandardCharsets.UTF_8)); fos.close(); } private static void Demo1() throws IOException { FileInputStream fis = new FileInputStream("chinese.txt"); byte[] arr = new byte[3]; String s; int len ; while ( ( len=fis.read(arr) ) != -1){ System.out.println(new String(arr,0,len)); } } } 异常处理 流初始化null try 关闭流 能关闭一个就关闭一个 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Demo10_IOException { public static void main(String[] args) throws IOException{ FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("test.txt"); fos = new FileOutputStream("copy.txt"); } finally { try{ if(null != fis){ fis.close(); } } finally { if(null != fos){ fos.close(); } } } } } 图片加密解密 加密把输出的字节异或一个数, 解密时再异或这个数 import java.io.*; public class Demo12_Encrypt { public static void main(String[] args) throws IOException { String src = "beauty.png"; String dest = "copy.png"; String dest2 = "copy1.png"; // extracted(src, dest); extracted(dest, dest2); } private static void extracted( String src, String dest) throws IOException { BufferedInputStream fis = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(dest)); int b ; while ( (b = fis.read()) != -1){ fos.write(b ^ 123 ); } fis.close(); fos.close(); } } 输入文件复制到当前路径下 import java.io.*; import java.util.Scanner; public class Demo13_CopyFile { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); String src = null; if(sc.hasNext()){ src = sc.nextLine(); } BufferedInputStream fis =null; int b ; BufferedOutputStream fos = null; if(src != null){ File file = new File(src); fis = new BufferedInputStream(new FileInputStream(src)); fos = new BufferedOutputStream(new FileOutputStream("./"+file.getName())); if( file.isFile()){ while ( (b = fis.read()) != -1){ fos.write(b); } } else if( file.isDirectory()){ System.out.println("文件夹无法复制"); } } fis.close(); fos.close(); } } 练习, 录入输入字符到文件中 import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class Demo14_InputKey { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("test.txt", true)); String input = null; while ( sc.hasNext()){ input = sc.nextLine(); if( "quit".equals(input)){ break; } else{ bos.write(input.getBytes(StandardCharsets.UTF_8)); bos.write("\n".getBytes(StandardCharsets.UTF_8)); } } bos.close(); } }

August 30, 2021 · 4 分钟 · Lizicai

Java的File类 Li.041

File 相对路径文件或目录 绝对路径文件或目录 File(String pathname) 文件路径或目录 File(String parent, String child) 父文件路径, 和子文件名 File(File parent, String child) 父文件路径file, 和子文件名 import java.io.File; public class Demo1_File { public static void main(String[] args) { // Demo1(); // Demo2(); File parentFile = new File("/usr/local/etc/nginx/"); String child = "nginx.conf"; File file = new File(parentFile, child); } private static void Demo2() { String parent = "/usr/local/etc/nginx/"; String child = "nginx.conf"; File file = new File(parent,child); System.out.println(file.exists()); } // a.c 与 src 在同级目录下 private static void Demo1() { File file = new File("/usr/local/etc/nginx/nginx.conf"); System.out.println(file.exists()); File file2 = new File("a.c"); System.out.println(file2.exists()); } } File 的方法 boolean createNewFile() throws IOException 如果没有则创建true, 有则不创建false. boolean mkdir() 无则创建文件夹, 有则不创建false boolean mkdirs() 无则创建多级文件夹, 有则不创建false import java.io.File; import java.io.IOException; public class Demo2_FileMethod { public static void main(String[] args) throws IOException { File file = new File("aaa.c"); System.out.println(file.createNewFile()); File file2 = new File("test"); System.out.println(file2.mkdir()); File file3 = new File("test/aaa"); System.out.println(file3.mkdirs()); } } boolean renameTo(File dest) 就是mv命令 boolean delete() 删除文件或删除空文件夹, 文件夹内有文件或文件夹(空的也算)则删除不了 import java.io.File; import java.io.IOException; public class Demo3_FileMethod { public static void main(String[] args) throws IOException { File file1 = new File("aaa.c"); File file2 = new File("bbb.c"); System.out.println(file1.renameTo(file2)); System.out.println(file2.delete()); File file3 = new File("test/aaa"); System.out.println(file3.delete()); File file4 = new File("test/ccc"); System.out.println(file4.mkdirs()); file4.delete(); File file5 = new File( "test"); System.out.println(file5.delete()); } } boolean isDirectory() 判断是否文件夹 boolean isFile() 判断是否文件 boolean exists() 判断是否存在 boolean canRead() 判断是否可读权限 boolean canWrite() 判断是否可写权限 boolean isHidden() 判断是否隐藏 import java.io.File; import java.io.IOException; public class Demo4_FileMethod { public static void main(String[] args) throws IOException { File file1 = new File("test"); System.out.println(file1.isDirectory()); File file2 = new File("test.c"); System.out.println(file1.isFile()); System.out.println(file2.isFile()); File file3 = new File("aaa.c"); System.out.println(file3.exists()); System.out.println(file3.createNewFile()); System.out.println(file3.exists()); File file4 = new File("ccc.c"); System.out.println(file4.createNewFile()); System.out.println(file4.canRead()); File file5 = new File("ddd.c"); System.out.println(file5.createNewFile()); System.out.println(file5.canWrite()); File file6 = new File("root.c"); System.out.println(file6.setReadable(false)); System.out.println(file6.canRead()); System.out.println(file6.canWrite()); File file7 = new File("test.c"); System.out.println(file7.isHidden()); File file8 = new File(".idea"); System.out.println(file8.isHidden()); } } String getAbsolutePath() String getPath() String getName() long length() long lastModified() String[] list() File[] listFiles() import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; public class Demo5_FileMethod { public static void main(String[] args) { File file = new File("aaa.c"); File file2 = new File("/Users/test/IdeaProjects/day19/"); System.out.println(file.getAbsoluteFile()); System.out.println(file2.getAbsoluteFile()); System.out.println(file.getPath()); System.out.println(file2.getPath()); System.out.println(file.getName()); System.out.println(file2.getName()); System.out.println(file.length()); System.out.println(file2.length()); System.out.println(file.lastModified()); System.out.println(file2.lastModified()); Date date = new Date(file.lastModified()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(simpleDateFormat.format(date)); String [] arr = file.list(); // for(String s: arr){ // System.out.println(s); // } String [] arr2 = file2.list(); for(String s: arr2){ System.out.println(s); } File[] list1 = file.listFiles(); // for(File f : list1){ // System.out.println(f); // } File[] list2 = file2.listFiles(); for(File f : list2){ System.out.println(f); } } } 练习 查找文件夹下所有的.c结尾的文件 遍历所有的文件, 碰到文件夹则进入遍历 文件名字正则匹配, 匹配输出 或使用String endsWith 匹配 import java.io.File; public class Demo6_FileTest { public static void main(String[] args) { File file = new File("/Users/test/workplace/test"); File file2 = new File("/Users/test/workplace/test"); File[] arrFile = file.listFiles(); File[] arrFile2 = file2.listFiles(); String regex = ".*[\\.][c]$"; String strEnd = ".c"; fileFind(arrFile, strEnd); fileFindRegex(arrFile2, regex); } public static void fileFind(File[] file, String strEnd){ for(File f : file){ if(f.isDirectory()){ fileFind(f.listFiles(), strEnd); } else{ if( f.getName().endsWith(strEnd) ){ System.out.println(f.getName()); } } } return ; } public static void fileFindRegex(File[] file, String regex){ for(File f : file){ if(f.isDirectory()){ fileFindRegex(f.listFiles(), regex); } else{ if( f.getName().matches(regex) ){ System.out.println(f.getName()); } } } return ; } } String[] list(FilenameFilter filter) 实现FilenameFilter 接口, 返回匹配的数组 原码 ...

August 29, 2021 · 3 分钟 · Lizicai

Java的异常类 Li.040

Java 的异常类 异常的体系 Throwable Error Exception RuntimeException 如果程序没有处理异常, JVM 自行处理, 把异常的名称和信息, 打印在控制台上. 异常的2种处理方式 try catch finally try catch try catch finally try finally throws public class Demo1_Exception { public static void main(String[] args) { Demo1 demo1 = new Demo1(); int x; try{ x = demo1.div(10,0); } catch (ArithmeticException e){ System.out.println(e.getClass()); System.out.println("test"); }finally { System.out.println("最后执行了吗"); } } } class Demo1 { public int div (int a, int b){ return a/b; } } public class Demo2_Exception { public static void main(String[] args) { int a = 0; int b = 10; int[] arr = {1, 2, 3}; int x ; arr = null; try { // x = b / a; System.out.println(arr[10]); } catch (ArithmeticException e){ System.out.println(e.getClass()); } catch (IndexOutOfBoundsException e){ System.out.println(e.getClass()); } catch (Exception e){ System.out.println("有异常"); } } } public class Demo3_Exception { public static void main(String[] args) { try { System.out.println(10/0); } catch (ArithmeticException | IndexOutOfBoundsException e){ System.out.println("Exception"); } } } 异常throwable 的方法 String getMessage() 获取异常信息 String toString() 获取异常类和异常信息 void printStackTrace() 获取异常类和异常信息, 异常在程序出现的位置 public class Demo3_Exception { public static void main(String[] args) { try { System.out.println(10/0); } catch (ArithmeticException | IndexOutOfBoundsException e){ System.out.println(e.getMessage()); System.out.println(e.toString()); e.printStackTrace(); } } } 方法上的2种异常 RuntimeException 运行时异常, 不需要在方法向上抛出, 使用的时候也不需要在使用的方法上向上抛出 非RuntimeException 的异常, 必须在方法上向上抛出, 使用方法时也必须向上抛出异常 import lombok.Getter; import lombok.Setter; public class Person { public Person(){} public Person(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter private int age; public void setAge(int age) { if(age < 1 || age > 150){ throw new RuntimeException ("年龄非法"); } this.age = age; } } import lombok.Getter; import lombok.Setter; public class Person { public Person(){} public Person(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter private int age; public void setAge(int age) throws Exception{ if(age < 1 || age > 150){ throw new Exception ("年龄非法"); } this.age = age; } } public class Demo4_Exception { public static void main(String[] args) throws Exception{ Person p = new Person(); p.setAge(-12); System.out.println("MM"); } } throws 和 throw 区别 throws 用在方法声明后, 跟的是异常类名 跟以跟多个类名, 用逗号隔开 表示抛出异常, 由该方法的调用者处理 throw 用在方法内, 跟的是异常对象名 只能抛出一个异常对象名 表示抛出异常, 由方法体内的语句处理 finally finally 的特点 被finally 控制的语句一定会执行 特殊情况: 在执行finally 前 JVM 退出了(如System.exit(0)) finally 的作用 用于释放资源, 在IO 操作和数据库操作中会见到 return 的区别 return 执行后, 如果有finally 则执行finally 类 public class Demo5_Exception { public static void main(String[] args) { try { System.out.println(1/0); } catch (Exception e){ System.out.println("异常"); } finally { System.out.println("最后一定执行"); } } } final finally finalize 区别 final final 可以修饰类, 但不能被继承 修饰方法不能被重写 修饰变量只能赋值一次 finally try catch finally 体系中的一个语句, 不能单独使用 finalize 当垃圾回收器确定不存在该对象的更多引用时, 对象回收器则调用此方法 public class Demo6_Exception { public static void main(String[] args) { System.out.println(demo1()); } public static int demo1(){ int x = 10; try { x = 20; System.out.println(1/0); return x; } catch (Exception e){ x = 30; return x; } finally { x = 40; } } } x 会返回30, return 把x=30装箱返回回去 ...

August 27, 2021&nbsp;·&nbsp;4 分钟&nbsp;·&nbsp;Lizicai

Java的Map类 Li.039

Map 将键映射到值的对象 一个映射不能包含重复的键 每个键最多只能映射到一个值 Map 与 Collection 接口的不同 Map 是双列的, Collection 是单列的 Map 是键唯一, Collection 的子体系Set是唯一的 Map 集合的数据结构值针对键有效, 跟值无关; Collection集合的数据结构是针对元素有效 Map 方法 V put(K key, V value) 添加键和值, 成功返回null, 覆盖重复key值, 则返回被覆盖的Value值 V remove(Object key) 通过key删除元素, 删除成功则返回Value值 boolean containsKey(Object key) Map 中是否包含Key值 boolean containsValue(Object value) Map 中是否包含Value值 boolean isEmpty() Map 是否为空 clear() 清空Map import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Demo1_Map { public static void main(String[] args) { // Demo1(); Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("小明", 18); hashMap.put("小红", 19); hashMap.put("小王", 20); System.out.println(hashMap); Integer i = hashMap.remove("小王"); System.out.println(i); System.out.println(hashMap); System.out.println(hashMap.containsKey("小明")); System.out.println(hashMap.containsValue(19)); System.out.println(hashMap.isEmpty()); Collection<Integer> v = hashMap.values(); System.out.println(v); hashMap.clear(); System.out.println(hashMap.size()); } private static void Demo1() { Map<String,Integer> map = new HashMap<>(); Integer i1 = map.put("s1",12); Integer i2 = map.put("s2",22); Integer i3 = map.put("s3",33); Integer i4 = map.put("s3",34); Integer i5 = map.put("s5",35); Integer i6 = map.put("s6",35); System.out.println(map); System.out.println(i4); System.out.println(i5); System.out.println(i6); } } Map 根据键获取值 import java.util.HashMap; public class Demo2_Iterator { public static void main(String[] args) { HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("a", 100); hashMap.put("b",90); hashMap.put("c",98); for(String s:hashMap.keySet()){ System.out.println(s + "="+ hashMap.get(s)); } } } Map 的键值对, 来获取Map中的Key 与 Value import java.util.HashMap; import java.util.Map; public class Demo3_Iterator { public static void main(String[] args) { HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("a", 90); hashMap.put("b",95); hashMap.put("c",98); for(Map.Entry<String,Integer> single: hashMap.entrySet()){ System.out.println(single.getKey() + " "+ single.getValue()); } } } HashMap 存入Student类和String时, 重写 hashCode 和 equals方法 import lombok.Getter; import lombok.Setter; import java.util.Objects; public class Student { public Student(){} public Student(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter @Setter private int age; @Override public String toString() { return "Student "+this.name+this.age; } @Override public int hashCode() { return Objects.hash(name, age); } @Override public boolean equals(Object obj) { Student s = (Student) obj; return this.name == s.name && this.age == s.age; } } import com.lizicai.bean.Student; import java.util.HashMap; public class Demo4_HashMap { public static void main(String[] args) { HashMap<Student, String> hashMap = new HashMap<>(); hashMap.put(new Student("小明",23), "上海"); hashMap.put(new Student("小明",23), "北京"); hashMap.put(new Student("小王",26), "北京"); hashMap.put(new Student("莱昂纳多",28), "美国"); System.out.println(hashMap); } } LinkedHashMap import java.util.LinkedHashMap; public class Demo5_LinkedHashMap { public static void main(String[] args) { LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put("a", 20); linkedHashMap.put("b", 20); linkedHashMap.put("c", 20); System.out.println(linkedHashMap); } } TreeMap 必须实现 Comparable 接口, 2种方式 方式一在bean类中实现Comparable 接口 import lombok.Getter; import lombok.Setter; import java.util.Objects; public class Student implements Comparable<Student>{ public Student(){} public Student(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter @Setter private int age; @Override public String toString() { return "Student "+this.name+this.age; } @Override public int hashCode() { return Objects.hash(name, age); } @Override public boolean equals(Object obj) { Student s = (Student) obj; return this.name == s.name && this.age == s.age; } @Override public int compareTo(Student o) { int numName = this.name.compareTo(o.name); int numAge = numName == 0 ? this.age-o.age : numName; return numAge; } } public class Demo6_TreeMap { public static void main(String[] args) { // Demo1(); TreeMap<Student, String> treeMap = new TreeMap<>(); treeMap.put(new Student("ab",23), "上海"); treeMap.put(new Student("ab",23), "北京"); treeMap.put(new Student("ac",26), "北京"); treeMap.put(new Student("abc",28), "美国"); System.out.println(treeMap); } } 方式二, 在创建TreeMap时实现 Comparator 接口 public static void main(String[] args) { TreeMap<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int numName = o1.getName().compareTo(o2.getName()); int numAge = numName == 0 ? o1.getAge()-o2.getAge() : numName; return numAge; } }); treeMap.put(new Student("ab",23), "上海"); treeMap.put(new Student("ab",23), "北京"); treeMap.put(new Student("ac",26), "北京"); treeMap.put(new Student("abc",28), "美国"); System.out.println(treeMap); } 练习, 字符串 aaabbbccccfgkj 统计字母出现次数 字母在Map里Key 没有, 由存入key,1, 有则存key, value+1 import java.util.HashMap; import java.util.Map; public class Demo7_HashMap { public static void main(String[] args) { HashMap<Character, Integer> hashMap = new HashMap<>(); String str = "aaabbbbccccd"; char[] cArray = str.toCharArray(); for(char c : cArray){ if( ! hashMap.containsKey(c)){ hashMap.put(c,1); } else { hashMap.put(c, hashMap.get(c)+1); } } for(Map.Entry<Character,Integer> ci:hashMap.entrySet()){ System.out.println(ci.getKey() + "=" + ci.getValue() ); } } } 练习 HashMap 嵌套 HashMap import lombok.Getter; import lombok.Setter; import java.util.Objects; public class Student implements Comparable<Student>{ public Student(){} public Student(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter @Setter private int age; @Override public String toString() { return "Student "+this.name+this.age; } @Override public int hashCode() { return Objects.hash(name, age); } @Override public boolean equals(Object obj) { Student s = (Student) obj; return this.name == s.name && this.age == s.age; } import com.lizicai.bean.Student; import java.util.HashMap; import java.util.Map; public class Demo8_HashMapHashMap { public static void main(String[] args) { HashMap<Student, String> hashMap1 = new HashMap<>(); hashMap1.put(new Student("小明",23), "上海"); hashMap1.put(new Student("小王",26), "北京"); hashMap1.put(new Student("莱昂纳多",28), "美国"); HashMap<Student, String> hashMap2 = new HashMap<>(); hashMap2.put(new Student("小明",23), "上海"); hashMap2.put(new Student("小王",26), "北京"); hashMap2.put(new Student("莱昂纳多",29), "美国"); HashMap<HashMap<Student,String>,String > hashMap = new HashMap<>(); hashMap.put(hashMap1,"班级1"); hashMap.put(hashMap2,"班级2"); for(Map.Entry<HashMap<Student,String>, String> HH : hashMap.entrySet()){ for(Map.Entry<Student,String> HHS : HH.getKey().entrySet()){ System.out.println(HHS.getKey() + HHS.getValue()+HH.getValue()); } } System.out.println(hashMap); } } HashMap 和 Hashtable 区别 共同点 都是双链集合 区别 HashMap 是线程不安全的, 效率高JDK 1.2 版本 Hashtable 是线程安全的, 效率低, JDK 1.0 版本 HashMap 可以存储null 键 和 null 值 Hashtable 不可以存储null 键 及 null 值 import java.util.HashMap; import java.util.Hashtable; public class Demo9_HashMapHashtable { public static void main(String[] args) { HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put(null, 10); hashMap.put("a", null); System.out.println(hashMap); Hashtable<String, Integer> hashtable = new Hashtable<>(); hashtable.put(null, 10); hashtable.put("a", null); System.out.println(hashtable); } } Collections 中的方法 static <T extends Comparable<? super T» void sort(List list) 排序 static int binarySearch(List<? extends Comparable<? super T» list, T key) 二分查找 static <T extends Object & Comparable<? super T» T max(Collection<? extends T> coll) 返回最大值 static void reverse(List<?> list) 反转列表 static void shuffle(List<?> list) list 序列洗牌 private static void Demo5() { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("d"); arrayList.add("a"); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("f"); System.out.println(arrayList); Collections.shuffle(arrayList); System.out.println(arrayList); } private static void Demo4() { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("d"); arrayList.add("a"); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("f"); System.out.println(arrayList); Collections.reverse(arrayList); System.out.println(arrayList); } private static void Demo3() { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("d"); arrayList.add("a"); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("f"); String max = Collections.max(arrayList); System.out.println(max); } private static void Demo2() { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("d"); arrayList.add("a"); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("a"); Collections.sort(arrayList); System.out.println(arrayList); int index = Collections.binarySearch(arrayList, "b"); System.out.println(index); System.out.println(Collections.binarySearch(arrayList,"o")); } private static void Demo1() { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("d"); arrayList.add("a"); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("a"); System.out.println(arrayList); Collections.sort(arrayList); System.out.println(arrayList); } 练习, 54 张牌, 每人17张, 剩下3张, 打印每个人牌和底牌 import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Demo2_Collections { public static void main(String[] args) { String[] nu = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; String[] color = { "♠️", "♥️", "♦️", "♣️"}; ArrayList<String> arrayList = new ArrayList<>(); for(String nuStr : nu){ for(String colorStr : color){ arrayList.add(nuStr + colorStr); } } arrayList.add("Big King"); arrayList.add("Small King"); for(int i=0;i<3;i++){ Collections.shuffle(arrayList); } System.out.println(arrayList); ArrayList<String> list1 = new ArrayList<>(); ArrayList<String> list2 = new ArrayList<>(); ArrayList<String> list3 = new ArrayList<>(); ArrayList<String> list4 = new ArrayList<>(); Scanner sc = new Scanner(System.in); for(int i=0;i<53;i++){ if(i >= 50 ){ list4.add(arrayList.get(i)); } else if( i % 3 == 0){ list1.add(arrayList.get(i)); } else if( i % 3 == 1) { list2.add(arrayList.get(i)); } else if( i % 3 ==2 ){ list3.add(arrayList.get(i)); } } System.out.println(list4); System.out.println(list1); System.out.println(list2); System.out.println(list3); } } 练习使用 HashMap 模拟一副牌 用HashMap 的 Key 生成arraylist来洗牌 import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeMap; public class Demo3_Collections { public static void main(String[] args) { HashMap<Integer, String> poker = new HashMap<>(); String[] nu = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2"}; String[] color = { "♠️", "♥️", "♦️", "♣️"}; int count = 0; ArrayList<Integer> pokerIndex = new ArrayList<>(); for(String nuStr : nu){ for(String colorStr : color){ poker.put(count, (colorStr + nuStr)); pokerIndex.add(count); count++; } } poker.put(count, "Small King"); pokerIndex.add(count); count++; poker.put(count, "Big King"); pokerIndex.add(count); TreeMap<Integer, String> gaojin = new TreeMap<>(); TreeMap<Integer, String> jp = new TreeMap<>(); TreeMap<Integer, String> tiger = new TreeMap<>(); TreeMap<Integer, String> dipai = new TreeMap<>(); System.out.println(pokerIndex.size()); Collections.shuffle(pokerIndex); System.out.println(pokerIndex); for(int i=0;i< pokerIndex.size(); i++){ int index = pokerIndex.get(i); if(i > 50){ dipai.put( index , poker.get( index)); } else if ( i % 3 == 0){ gaojin.put( index, poker.get(index )); } else if (i % 3 == 1){ jp.put( index , poker.get( index )); } else if (i % 3 == 2){ tiger.put( index, poker.get( index )); } } System.out.println(gaojin); System.out.println(jp); System.out.println(tiger); System.out.println(dipai); } } ? Super E 情况 TreeSet TreeMap 会调用 import lombok.Getter; import lombok.Setter; import java.util.Objects; public class Student implements Comparable<Student>{ public Student(){} public Student(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter @Setter private int age; @Override public String toString() { return "Student "+this.name+this.age; } @Override public int hashCode() { return Objects.hash(name, age); } @Override public boolean equals(Object obj) { Student s = (Student) obj; return this.name == s.name && this.age == s.age; } @Override public int compareTo(Student o) { int numName = this.name.compareTo(o.name); int numAge = numName == 0 ? this.age-o.age : numName; return numAge; } } public class BaseStudent extends Student{ public BaseStudent(){} public BaseStudent(String name, int age){ super(name, age); } } import com.lizicai.bean.BaseStudent; import com.lizicai.bean.Student; import java.util.ArrayList; import java.util.Comparator; import java.util.TreeSet; public class Demo4_Generic { public static void main(String[] args) { // Demo1(); TreeSet<Student> treeSet = new TreeSet<>(new CompareByAge()); treeSet.add(new Student("小明",22)); treeSet.add(new Student("小红",22)); treeSet.add(new Student("小王",22)); System.out.println(treeSet); TreeSet<BaseStudent> treeSet2 = new TreeSet<>(new CompareByAge()); treeSet2.add(new BaseStudent("小明",22)); treeSet2.add(new BaseStudent("小红",22)); treeSet2.add(new BaseStudent("小王",22)); System.out.println(treeSet2); } private static void Demo1() { ArrayList<Student> arrayList = new ArrayList<>(); arrayList.add(new Student("小明",22)); arrayList.add(new Student("小红",22)); arrayList.add(new Student("小王",22)); ArrayList<BaseStudent> arrayList2 = new ArrayList<>(); arrayList2.add(new BaseStudent("小明",22)); arrayList2.add(new BaseStudent("小红",22)); arrayList2.add(new BaseStudent("小王",22)); arrayList.addAll(arrayList2); System.out.println(arrayList); } } class CompareByAge implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { int num = o1.getAge() - o2.getAge(); int numName = num == 0 ? o1.getName().compareTo(o2.getName()): num; return numName; } } Collection List 存取有序, 有索引, 可重复 ArrayList 底层数组实现的, 线程不安全, 查找修改快, 增删慢 LinkedList 底层是链表实现的, 线程不安全, 查找慢, 增删快 Vetor 底层数组实现的, 线程安全, 查找修改增删都慢 如果查找修改多用ArrayList, 增和删多用LinkedList, 如果都多用ArrayList ...

August 24, 2021&nbsp;·&nbsp;8 分钟&nbsp;·&nbsp;Lizicai

Java的Set类 Li.038

Set 无序 不可重复 import java.util.HashSet; public class Demo1_HashSet { public static void main(String[] args) { HashSet<String> hs = new HashSet<>(); boolean b1 = hs.add("a"); boolean b2 = hs.add("a"); System.out.println(hs); System.out.println(b1+" "+b2); for(String s:hs){ System.out.println(s); } } } HashSet 的重写hashCode() 方法, hashCode值一致时, 调用equals方法 使用HashSet 存取元素时, 这个元素必须重写 hashCode 和 equals方法 import lombok.Getter; import lombok.Setter; import java.util.Objects; public class Person { public Person(){} public Person(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter @Setter private int age; @Override public String toString(){ return "Person" + this.getName() + this.getAge(); } @Override public boolean equals(Object obj) { Person p = (Person) obj; return this.getName() == p.getName() && this.getAge() == p.getAge(); } @Override public int hashCode() { return Objects.hash(name, age); } } public static int hashCode(Object a[]) { if (a == null) return 0; int result = 1; for (Object element : a) result = 31 * result + (element == null ? 0 : element.hashCode()); return result; } LinkedHashSet 底层链表实现的 是Set对象中唯一一个保证怎么存就怎么取的集合对象 HashSet的子类, 也是保证元素是唯一的 import java.util.LinkedHashSet; public class Demo1_LinkedHashSet { public static void main(String[] args) { LinkedHashSet <String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add("a"); linkedHashSet.add("a"); linkedHashSet.add("b"); linkedHashSet.add("b"); linkedHashSet.add("b"); linkedHashSet.add("c"); System.out.println(linkedHashSet); } } HashSet 练习, 放入集合10个[1,20]的整数 import java.util.HashSet; import java.util.Random; public class Demo1_Test { public static void main(String[] args) { Random r = new Random(); HashSet <Integer> hashSet = new HashSet<>(); while(hashSet.size() < 10 ){ Integer i = r.nextInt(20) + 1; hashSet.add(i); } System.out.println(hashSet); } } HashSet 练习, 输入一串字符串, 去掉重复字符 import java.util.HashSet; import java.util.Scanner; public class Demo2_Test { public static void main(String[] args) { HashSet<Character> hs = new HashSet<>(); Scanner sc = new Scanner(System.in); String s = null; if(sc.hasNext()){ s = sc.nextLine(); } char[] charArray= s.toCharArray(); // for(Character c:charArray){ for(char c:charArray){ hs.add(c); } System.out.println(hs); } } HashSet 练习, list 去重, 并返回元素list import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; public class Demo3_Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("b"); list.add("c"); list.add("c"); list.add("c"); HashSet <String> hs = new LinkedHashSet<>(); // deleteCopyElement(list, hs); deleteCopyE(list); // System.out.println(hs); System.out.println(list); } public static void deleteCopyElement(List<String> list, HashSet<String> hashSet){ hashSet.addAll(list); list.clear(); list.addAll(hashSet); } public static void deleteCopyE(List<String> list){ LinkedHashSet<String> hs = new LinkedHashSet<>(); hs.addAll(list); list.clear(); list.addAll(hs); } } TreeSet 集合, 对集合进行排序的, 元素唯一 保证元素唯一 集合排序 import java.util.TreeSet; public class Demo1_TreeSet { public static void main(String[] args) { TreeSet <Integer> ts = new TreeSet<>(); ts.add(1); ts.add(1); ts.add(2); ts.add(2); ts.add(3); ts.add(3); System.out.println(ts); } } TreeSet , 类实现Comparable接口 compareTo 方法返回0, 则集合中只用一个元素 compareTo 方法返回正数, 集合怎么存怎么取 compareTo 方法返回负数, 集合倒序存储 import lombok.Getter; import lombok.Setter; import java.util.Objects; public class Person implements Comparable <Person>{ public Person(){} public Person(String name, int age){ this.name = name; this.age = age; } @Getter @Setter private String name; @Getter @Setter private int age; @Override public String toString(){ return "Person" + this.getName() + this.getAge(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Person)) { return false; } Person person = (Person) o; return getAge() == person.getAge() && Objects.equals(getName(), person.getName()); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public int compareTo(Person p) { int num = this.age - p.age; return num == 0 ? this.name.compareTo(p.name) : num; } } public class Demo1_TreeSet { public static void main(String[] args) { TreeSet<Person> ts = new TreeSet<>(); ts.add(new Person("小明", 20)); ts.add(new Person("小红", 19)); ts.add(new Person("小张", 21)); ts.add(new Person("小张", 21)); System.out.println(ts); } } TreeSet 如果使用Person 的name排序, 则需要实现Compareable 接口, compareTo方法 @Override public int compareTo(Person p) { int num = this.name.compareTo(p.name); return num == 0 ? this.age-p.age : num; } public class Demo1_TreeSet { public static void main(String[] args) { TreeSet<Person> ts = new TreeSet<>(); ts.add(new Person("a", 20)); ts.add(new Person("a", 19)); ts.add(new Person("ab", 19)); ts.add(new Person("ba", 21)); ts.add(new Person("ca", 21)); System.out.println(ts); } } TreeSet 使用Person 的name长度比较 @Override public int compareTo(Person p){ int length = this.name.length()- p.name.length(); int num = length == 0 ? this.name.compareTo(p.name) : length; return num == 0 ? this.age - p.age : num; } TreeSet 实现Comparator接口, 在创建TreeSet时调用 自动定义String 长度作为比较 class Compare implements Comparator<String>{ @Override public int compare(String o1, String o2) { int length = o1.length() - o2.length(); int num = length == 0 ? o1.compareTo(o2) : length; return num; } } public class Demo4_TreeSet { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<>(new Compare()); ts.add("asdfsdf"); ts.add("z"); System.out.println(ts); } } 练习, ArrayList 重复无序的数据, 如何按字典排序, 且不可去除重复数据 import java.util.ArrayList; import java.util.Comparator; import java.util.TreeSet; public class Demo5_TreeSet { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<>(); aList.add("aaa"); aList.add("aaa"); aList.add("aaa"); aList.add("bbb"); aList.add("bbb"); aList.add("bbb"); aList.add("bbb"); aList.add("aaa"); aList.add("aaa"); aList.add("zzz"); aList.add("zzz"); aList.add("zzz"); sortArrayList(aList); System.out.println(aList); } public static void sortArrayList(ArrayList<String> list){ // 实际Comparator // list添加到tree(new comparator)中 // 清空list // list.addAll(TreeSet) TreeSet<String> ts = new TreeSet<>(new StrComparator()); ts.addAll(list); list.clear(); list.addAll(ts); } } class StrComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { int num = o1.compareTo(o2); if(0 == num){ num ++; } return num; } } 练习, 输入字符hello 输出ehllo import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; public class Demo6_TreeSet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = null; if(sc.hasNext()){ s = sc.nextLine(); } char[] chaArray = s.toCharArray(); // Arrays.sort(chaArray); // System.out.println(chaArray); TreeSet<Character> ts = new TreeSet<>(new Comparator<Character>() { @Override public int compare(Character o1, Character o2) { int num = o1.compareTo(o2); return num == 0? 1 :num; } }); for(Character c:chaArray){ ts.add(c); } for(Character c:ts){ System.out.print(c); } } } 练习, 输入数字并倒序 输入quit 退出 import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; public class Demo7_TreeSet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { int num = o2.compareTo(o1); return num == 0 ? 1 :num ; } }); while (sc.hasNext()){ String s = sc.next(); if( "quit".equals(s)){ break; } else{ ts.add(Integer.parseInt(s)); } } for(Integer i:ts){ System.out.print(i+" "); } } } 练习 录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩) 按总成绩从高到低输入到控制台 import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @AllArgsConstructor @NoArgsConstructor public class Student implements Comparable<Student>{ @Getter @Setter private String name; @Getter @Setter private int motherTongue; @Getter @Setter private int math; @Getter @Setter private int english; @Override public int compareTo(Student o) { int num = (o.motherTongue + o.math + o.english) - (this.motherTongue + this.math + this.english); int num2 = num == 0 ? o.motherTongue - this.motherTongue : num; int num3 = num2 == 0 ? o.math - this.math : num2; int num4 = num3 == 0 ? o.english - this.english : num3; int num5 = num4 == 0 ? o.name.compareTo(this.name) : num4 ; if (0 == num5){ num5 = -1; } return num5; } @Override public String toString() { return "Student."+this.name +".语文"+this.motherTongue+".数学"+this.math+".英语" + this.english; } } import com.lizicai.bean.Student; import java.util.Scanner; import java.util.TreeSet; public class Demo8_TreeSet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); TreeSet<Student> ts = new TreeSet<>(); for(int i=0; i<5;i++){ String str = null; if(sc.hasNext()){ str = sc.nextLine(); } String[] strArray = str.split(","); ts.add(new Student(strArray[0], Integer.parseInt(strArray[1]), Integer.parseInt(strArray[2]), Integer.parseInt(strArray[3]))); } System.out.println(ts); } }

August 22, 2021&nbsp;·&nbsp;6 分钟&nbsp;·&nbsp;Lizicai

Java的List类 Li.037

List 练习Person 集合去重 @Data @AllArgsConstructor @NoArgsConstructor public class Person { private String name; private int age; @Override public boolean equals(Object obj) { Person p = (Person) obj; boolean d = false; if(this.getAge() == p.getAge() && this.getName() == p.getName()){ d = true; } else{ d = false; } return d; } } import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Demo2_ArrayList { public static void main(String[] args) { List list = new ArrayList(); list.add(new Person("小明", 23)); list.add(new Person("小明", 23)); list.add(new Person("小红", 22)); list.add(new Person("小王", 25)); List list2 = new ArrayList(); deleteMu(list, list2); System.out.println(list2); } public static void deleteMu(List srcList, List destList){ Iterator iTsrc = srcList.iterator(); while (iTsrc.hasNext()){ Person p = (Person) iTsrc.next(); if( !destList.contains(p) ){ destList.add(p); } } return ; } } LinkedList 方法 void addFirst(E e) void addLast(E e) 在头增加 或 在尾增加 public E getFirst() public E getLast() 获取第1个 或 最后1个 public E removeFirst() public E removeLast() 删除第1个或最后1个 public E get(int index) 获取指定位置的元素 import java.util.LinkedList; public class Demo1_LinkedList { public static void main(String[] args) { LinkedList ll = new LinkedList(); ll.add("a"); ll.add("b"); ll.add("c"); ll.add("d"); ll.addFirst(0); ll.addLast(10); System.out.println(ll); System.out.println(ll.getFirst()); System.out.println(ll.getLast()); ll.removeFirst(); System.out.println(ll); ll.removeLast(); System.out.println(ll); System.out.println(ll.get(0)); } } LinkedList 模拟栈 import lombok.Data; import java.util.LinkedList; @Data public class Stank { private LinkedList ll = new LinkedList(); public void in(Object obj){ ll.addLast(obj); } public void out(){ ll.removeLast(); } public void outAll(){ while (! ll.isEmpty()){ ll.removeLast(); } } public boolean isEmpty(){ if(ll.isEmpty()){ return true; } return false; } } import com.lizicai.bean.Stank; public class Demo3_LinkedList { public static void main(String[] args) { Stank s = new Stank(); s.in("a"); s.in("b"); s.in("c"); s.out(); System.out.println(s.getLl()); s.outAll(); System.out.println(s.getLl()); } } 泛型 generic 泛型的好处 提高安全性, 把运行的错误转移到编译时校验 省去强转的麻烦 前后泛型一致, 或者后面泛型是前端泛型的子类 ...

August 20, 2021&nbsp;·&nbsp;5 分钟&nbsp;·&nbsp;Lizicai

Java的Collection集合一 Li.036

Collection 和 数组区别 数组可以存储基本数据类型, 也可以存储引用数据类型 集合可以存储引用数据类型, 也能存基本数据类型, 存储时会自动装箱 数组的长度固定, 不可以自由增加 集合长度可变, 可以自由增加 List Set 集合 List 有序集合, 存取位置一致 有索引 可存储重复数据 Set 无序集合, 存取位置不一致 无索引 不可存储重复数据 List 体系 ArrayList LinkedList Vector ArrayList 底层是数组, 查询快, 增删慢 线程不安全, 效率高 LinkedList 链表实现, 查询慢, 增删快 线程不安全, 效率高 Vection 数组实现, 查询快, 增删慢 线程安全, 效率低 Set 体系 HashSet TreeSet HashSet 哈希算法 TreeSet 二叉树算法 ArrayList 的 boolean add(E e) 方法一直返回true, Set 集合存取重复元素时, 则返回false boolean remove(Object o) 一次删除一个对象 int size() 打印集合对象数 void clear() 清空集合 boolean isEmpty() 判断集合是否为空 public class Demo2_Collection { public static void main(String[] args) { Collection collection = new ArrayList(); boolean b1 = collection.add("abc"); boolean b2 = collection.add(true); boolean b3 = collection.add(100); boolean b4 = collection.add(new Student("小红",18)); boolean b5 = collection.add("abc"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); System.out.println(collection); System.out.println(collection.contains("abc")); collection.remove("abc"); System.out.println(collection); collection.remove("abc"); System.out.println(collection.size()); System.out.println(collection); System.out.println(collection.isEmpty()); collection.clear(); System.out.println(collection.isEmpty()); System.out.println(collection); } } Object[] toArray() 集合转换成数组 import com.lizicai.bean.Student; import java.util.ArrayList; import java.util.Collection; public class Demo3_Collection { public static void main(String[] args) { Collection c = new ArrayList(); c .add( new Student("小明", 24)); c .add( new Student("小红", 22)); c .add( new Student("小张", 30)); Object [] oArray = c.toArray(); for(Object o:oArray){ if( o instanceof Student){ Student s = (Student) o; System.out.println(s.getName()+s.getAge()); } else{ System.out.println(o); } } } } List 中带有All的方法 boolean addAll(Collection<? extends E> c) 添加另一个集合 boolean removeAll(Collection<?> c) 移除集合中所有与C集合一样的元素 boolean containsAll(Collection<?> c) 返回结果c集合全部 是 调用集合内元素的判断结果 boolean retainAll(Collection<?> c) 调用集合和c集合取交集, 调用集合改变则是true, 没改是false private static void Demo4() { Collection c = new ArrayList(); c.add("a"); c.add("b"); c.add("c"); Collection c2 = new ArrayList(); c2.add("a"); c2.add("b"); System.out.println(c.retainAll(c2)); System.out.println(c); } private static void Demo3() { Collection c = new ArrayList(); c.add("a"); c.add("b"); c.add("b"); c.add("c"); Collection c2 = new ArrayList(); c2.add("a"); c2.add("b"); c2.add("c"); System.out.println(c.containsAll(c2)); System.out.println(c); System.out.println(c2); } private static void Demo2() { Collection c = new ArrayList(); c.add("a"); c.add("b"); c.add("b"); c.add("c"); Collection c2 = new ArrayList(); c2.add("a"); c2.add("b"); c2.add("cc"); c.removeAll(c2); System.out.println(c); } private static void Demo1() { Collection c = new ArrayList(); c.add("a"); c.add("b"); c.add("c"); Collection c2 = new ArrayList(); c2.add("aa"); c2.add("bb"); c2.add("cc"); c.addAll(c2); c2.add(c); System.out.println(c); System.out.println(c2); } 集合的迭代器遍历 import com.lizicai.bean.Student; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Demo1_Iterator { public static void main(String[] args) { Collection c = new ArrayList(); c.add(new Student("小明", 24)); c.add(new Student("小红", 22)); c.add(new Student("小张", 30)); Iterator it = c.iterator(); while (it.hasNext()){ Object obj = it.next(); if( obj instanceof Student){ Student s = (Student)obj; System.out.println(s.getName()+s.getAge()); } else { System.out.println(obj); } } } } List 集合 void add(int index, E element) E remove(int index) E get(int index) E set(int index, E element) import java.util.ArrayList; import java.util.List; public class Demo1_List { public static void main(String[] args) { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); list.add(0,"d"); System.out.println(list); list.remove(0); System.out.println(list); list.set(2,"w"); System.out.println(list); System.out.println(list.get(2)); } } List 遍历的2种方式 for循环 iterator迭代器 public class Demo2_List { public static void main(String[] args) { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); } Iterator it = list.iterator(); while (it.hasNext()){ System.out.println(it.next()); } } } List 的 ListIterator 可以在遍历的时候添加元素, List不能在遍历的时候添加元素 import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class Demo3_List { public static void main(String[] args) { List list = new ArrayList(); list.add("a"); list.add("ab"); list.add("abc"); list.add("Hello"); // Iterator li = list.iterator(); // while (li.hasNext()){ // String s = (String)li.next(); // if("Hello".equals(s)){ // list.add("World"); // } // System.out.println(s); // } ListIterator li = list.listIterator(); while (li.hasNext()){ String s = (String)li.next(); if("Hello".equals(s)){ li.add("World"); } } System.out.println(list); } } Vector import java.util.Enumeration; import java.util.Vector; public class Demo1_Vector { public static void main(String[] args) { Vector v = new Vector(); v.addElement("a"); v.addElement("b"); v.addElement("c"); v.addElement("d"); Enumeration en = v.elements(); while (en.hasMoreElements()){ System.out.println(en.nextElement()); } } }

August 19, 2021&nbsp;·&nbsp;3 分钟&nbsp;·&nbsp;Lizicai

Java的正则表达式 Li.035

Java 的正则表达式Regex java.util.regex.Pattern 有正则表达示例 /* [abc] a, b, or c (simple class) abc中任意一个字符 [^abc] Any character except a, b, or c (negation) 非abc的一个字符 [a-zA-Z] a through z or A through Z, inclusive (range) 匹配a-z A-Z 大小写字符 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union) 匹配a-d 和 匹配 m-p 字符, 匹配则true [a-z&&[def]] d, e, or f (intersection) 匹配def 与 a-z的并集是 def [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction), 非bc 和 a-z取并集(匹配a d-z字符) [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction), 非m-p字符与a-z取并集, 并集是a-l和q-z */ private static void Demo7() { String regex = "[a-z&&[^m-p]]"; System.out.println("a".matches(regex)); System.out.println("n".matches(regex)); } private static void Demo6() { String regex = "[a-z&&[^bc]]"; System.out.println("a".matches(regex)); System.out.println("b".matches(regex)); } private static void Demo5() { String regex = "[a-z&&[def]]"; System.out.println("m".matches(regex)); System.out.println("a".matches(regex)); System.out.println("d".matches(regex)); } private static void Demo4() { String regex = "[a-d[x-z]]"; System.out.println("m".matches(regex)); System.out.println("a".matches(regex)); System.out.println("x".matches(regex)); } private static void Demo3() { String regex = "[a-zA-Z]"; System.out.println("a".matches(regex)); System.out.println("*".matches(regex)); } private static void Demo2() { String regex = "[^abc]"; System.out.println("a".matches(regex)); System.out.println("d".matches(regex)); System.out.println("10".matches(regex)); } private static void Demo1() { String regex = "[abc]"; System.out.println("a".matches(regex)); System.out.println("d".matches(regex)); } 正则预先定义的字符 public class Demo4_Regex { public static void main(String[] args) { /* . Any character (may or may not match line terminators) 匹配任何字符 \d A digit: [0-9] 0-9字符, 其他字符则false \D A non-digit: [^0-9] 非 0-9 字符, 0-9字符则false \h A horizontal whitespace character: [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000] 水平空白字符 \H A non-horizontal whitespace character: [^\h] 非水平空白字符 \s A whitespace character: [ \t\n\x0B\f\r] 空白字符 \S A non-whitespace character: [^\s] 非空白字符 \v A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029] 垂直空白字符 \V A non-vertical whitespace character: [^\v] 非垂直空白字符 \w A word character: [a-zA-Z_0-9] 大小写 数字 下划线 \W A non-word character: [^\w] 除大小写 数字 下划线 以外字符 */ } private static void Demo5() { // 字符 \w a-zA-Z0-9_ \W, 除去a-zA-Z0-9_的字符 String regex = "\\w"; System.out.println("s".matches(regex)); System.out.println("_".matches(regex)); System.out.println("0".matches(regex)); System.out.println("&".matches(regex)); String regex2 = "\\W"; System.out.println("s".matches(regex2)); System.out.println("_".matches(regex2)); System.out.println("0".matches(regex2)); System.out.println("&".matches(regex2)); } private static void Demo4() { String regex = "\\v"; System.out.println(" ".matches(regex)); System.out.println("\t".matches(regex)); System.out.println("\n".matches(regex)); System.out.println("a".matches(regex)); String regex2 = "\\V"; System.out.println(" ".matches(regex2)); System.out.println("\t".matches(regex2)); System.out.println("\n".matches(regex2)); System.out.println("a".matches(regex2)); } private static void Demo3() { String regex = "\\s"; System.out.println(" ".matches(regex)); System.out.println("\t".matches(regex)); System.out.println("\n".matches(regex)); System.out.println("a".matches(regex)); String regex2 = "\\S"; System.out.println(" ".matches(regex2)); System.out.println("\t".matches(regex2)); System.out.println("\n".matches(regex2)); System.out.println("a".matches(regex2)); } private static void Demo2() { String regex = "\\h"; String regex2 = "\\H"; System.out.println("a".matches(regex)); System.out.println(" ".matches(regex)); System.out.println("\t".matches(regex)); System.out.println("\n".matches(regex)); System.out.println("a".matches(regex2)); System.out.println(" ".matches(regex2)); System.out.println("\t".matches(regex2)); System.out.println("\n".matches(regex2)); } private static void Demo1() { String regex = "\\d"; System.out.println("a".matches(regex)); System.out.println("9".matches(regex)); String regex2 = "\\D"; System.out.println("a".matches(regex2)); System.out.println("9".matches(regex2)); } private static void Demo() { String regex = "."; System.out.println("a".matches(regex)); System.out.println("%".matches(regex)); System.out.println("9".matches(regex)); } } 正则匹配 出现次数 public class Demo5_Regex { public static void main(String[] args) { /* X? X, once or not at all X出现一次或一次也没有, 但是不能出现其他内容 X* X, zero or more times X出现0次或>0次, 但是不能出现其它内容 X+ X, one or more times X出现1次或>1次, 但是不能出现其它内容 X{n} X, exactly n times X准确出现n次, 不多不少, 但是不能出现其它内容 X{n,} X, at least n times X出现次数至少n次, 但是不能出现其它内容 X{n,m} X, at least n but not more than m times X出现次数 至少n次, 不超过m次, 记[n, m)次 */ } private static void Demo6() { String regex = "[abc]{2,4}"; System.out.println("a".matches(regex)); System.out.println("ab".matches(regex)); System.out.println("aba".matches(regex)); System.out.println("abca".matches(regex)); System.out.println("abcabc".matches(regex)); System.out.println(" ".matches(regex)); } private static void Demo5() { String regex = "[abc]{5,}"; System.out.println("abca".matches(regex)); System.out.println("abcab".matches(regex)); System.out.println("abcabc".matches(regex)); System.out.println("dkfjkf".matches(regex)); } private static void Demo4() { String regex = "[abc]{5}"; System.out.println("abca".matches(regex)); System.out.println("abccc".matches(regex)); System.out.println("abcabc".matches(regex)); System.out.println("abccd".matches(regex)); System.out.println("d".matches(regex)); System.out.println(" ".matches(regex)); } private static void Demo3() { String regex = "[abc]+"; System.out.println("a".matches(regex)); System.out.println("abc".matches(regex)); System.out.println("abcabccc".matches(regex)); System.out.println("abcd".matches(regex)); System.out.println("".matches(regex)); System.out.println("d".matches(regex)); } private static void Demo2() { String regex = "[abc]*"; System.out.println("".matches(regex)); System.out.println("a".matches(regex)); System.out.println("b".matches(regex)); System.out.println("bb".matches(regex)); System.out.println("abc".matches(regex)); System.out.println(" ".matches(regex)); System.out.println("s".matches(regex)); } private static void Demo1() { String regex = "[abc]?"; System.out.println("".matches(regex)); System.out.println("a".matches(regex)); System.out.println("b".matches(regex)); System.out.println(" ".matches(regex)); System.out.println("bb".matches(regex)); System.out.println("s".matches(regex)); } } String 中的 split 方法 String[] split(String regex) 匹配正则分隔成字符串数组 // 空格或问号出现1次或以上, 分隔 public class Demo6_Regex { public static void main(String[] args) { String str = "What is a youth?"; String regex = "[\\s\\?]+"; String [] strArray = str.split(regex); for(String s:strArray){ System.out.println(s); } } } 练习 字符串的数组, 经过排序后, 再转换成字符串 字符串, 分隔成字符串组 字符串组 转换为 数组 数组排序 数组重新转换为字符串 public class Demo1_Split { public static void main(String[] args) { String str = "1 10 2 30 100 40"; String regex = "[\\s]+"; String [] strArray = str.split(regex); int [] a = new int[strArray.length]; for(int i=0;i<strArray.length;i++){ a[i] = Integer.parseInt(strArray[i]); } StringBuffer sb = new StringBuffer(); Arrays.sort(a); if(a.length <1){ sb = sb.append("{}"); } else{ sb.append("{"); for (int i=0;i<a.length;i++){ if(i == a.length-1){ sb.append(a[i] + "}"); break; } sb.append(a[i] + " "); } } System.out.println(sb); } } 正则匹配, 替换字符 public class Demo2_Replace { public static void main(String[] args) { String str = "What2is2a233youth?"; String regex = "[\\d]"; String res = str.replaceAll(regex,""); System.out.println(res); String regex2 = "[\\d]"; String res2 = str.replaceAll(regex2," "); System.out.println(res2); String regex3 = "[\\d]+"; String res3 = str.replaceAll(regex3," "); System.out.println(res3); } } 正则匹配, 组 捕获 ((A)(B(C))) , 组是以左括号为一组, 所有共有 4 组 ((A)(B(C))) (A) (B(C)) (C) 正则匹配, 组的练习 public class Demo4_Replace { public static void main(String[] args) { // Demo1(); String str = "我...我...我...我....想想........学编...编...程....程...程程.."; String regex = "[\\.]+"; String str2 = str.replaceAll(regex, ""); System.out.println(str2); String regex2 = "(.)\\1+"; String str3 = str2.replaceAll(regex2, "$1"); System.out.println(str3); } private static void Demo1() { String str = "abchhhhkdjflllljkklqqqq"; String regex = "(.)\\1+"; String[] strArray = str.split(regex); for(String s:strArray){ System.out.println(s); } } } 正则匹配, Pattern 和 Matcher, 练习获取手机号 考虑手机号第2位一直在增加, 以1开头11位即认为正确手机号 public static void main(String[] args) { String str = "我用过的手机号12310001000, 上一个手机号是12310001001, 目前在用的12310001002"; String regex = "[1][\\d]{10}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); while (m.find()){ System.out.println(m.group()); } } Math 类 public class Demo1_Math { public static void main(String[] args) { System.out.println(Math.PI); System.out.println(Math.abs(-120)); // 向上取整 (0,1] System.out.println(Math.ceil(23.8)); System.out.println(Math.ceil(23.1)); // 向下取整 [0,1) System.out.println(Math.floor(23.8)); System.out.println(Math.floor(24.0)); System.out.println(Math.max(23,30)); System.out.println(Math.pow(3,3)); // 包含 [0.0,1.0) System.out.println(Math.random()); System.out.println(Math.sqrt(2)); } } Random 随机数 Random 是伪随机数, 生成的随机数由随机因子决定的 nextInt(100) 可以生成[0,100) 的随机整数 import java.util.Random; public class Demo1_Random { public static void main(String[] args) { Random r = new Random(); for(int i=0;i<10;i++){ int a = r.nextInt(100); System.out.println(a); } Random r2 = new Random(1000); int a1 = r2.nextInt(); int a2 = r2.nextInt(); System.out.println(a1); System.out.println(a2); // 执行多少次 a1 和 a2 固定 } } System 类 System.in 输入流, Scanner 录收键盘 System.out 输出控制台 System.gc() 垃圾回收 System.currentTimeMillis() 到1971年的毫秒, 2次时间差就能知道程序运行时间 exit() 退出 0 正常终止, 非0 异常终止 arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 数组复制, int str 对象等都可复制 public class Demo1_System { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); System.out.println("jkdjf"); System.out.println(System.currentTimeMillis()); long start = System.currentTimeMillis(); for(int i=0;i<10000000;i++){ System.out.print(""); StringBuffer sf = new StringBuffer(); } long end = System.currentTimeMillis(); System.out.println(end-start); for(int i=0;i<10;i++){ new Test(); System.gc(); } int [] src = {1, 2, 3, 4, 5}; int [] dest = new int[8]; System.arraycopy(src, 0, dest,0,src.length); for(int i:dest){ System.out.println(i); } } } class Test{ Test(){} @Override public void finalize(){ System.out.println("垃圾回收"); } } BigInteger 类 import java.math.BigInteger; public class Demo1_BigInteger { public static void main(String[] args) { BigInteger bi1 = new BigInteger("100"); BigInteger bi2 = new BigInteger("3"); System.out.println(bi1.add(bi2)); System.out.println(bi1.subtract(bi2)); System.out.println(bi1.multiply(bi2)); System.out.println(bi1.divide(bi2)); BigInteger [] bArray; bArray = bi1.divideAndRemainder(bi2); for(BigInteger b:bArray){ System.out.println(b); } } } BigDecimal, 金融运算使用 static BigDecimal valueOf(double val) 由double 转为 BigDecimal 构造函数时BigDecimal(String val), string 转为 BigDecimal public class Demo1_BigDecimal { public static void main(String[] args) { System.out.println(2.0 - 1.1 ); BigDecimal bd1 = new BigDecimal(2.0); BigDecimal bd2 = new BigDecimal(1.1); System.out.println(bd1.subtract(bd2)); BigDecimal bd3 = new BigDecimal("2.0"); BigDecimal bd4 = new BigDecimal("1.1"); System.out.println(bd3.subtract(bd4)); BigDecimal bd5 = BigDecimal.valueOf(2.0); BigDecimal bd6 = BigDecimal.valueOf(1.1); System.out.println(bd5.subtract(bd6)); } } Date 类 System.currentTimeMillis date.getTime() 都是与GMT 1970 01 01 00:00:00 的毫秒值 public class Demo1_Date { public static void main(String[] args) { // Demo1(); Date date = new Date(); System.out.println(date.getTime()); System.out.println(System.currentTimeMillis()); date.setTime(2000); System.out.println(date); } private static void Demo1() { Date date = new Date(); System.out.println(date); Date date2 = new Date(0); System.out.println(date2); } } SimpleDateFormat Date 特定格式输出 字符串转为Date import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo1_DateFormat { public static void main(String[] args) throws ParseException { // Demo1(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss E"); String strDate = "2021年08月18日 23:44:59 星期三"; Date date = sdf.parse(strDate); System.out.println(date); } private static void Demo1() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss E"); System.out.println(sdf.format(date)); } } SimpleDateFormat 练习, 从生日到现在多少天了 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo2_DateFormat { public static void main(String[] args) throws ParseException { String strDate = "1991-01-01"; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date birthday = sdf.parse(strDate); long days = date.getTime() - birthday.getTime(); System.out.println(days/1000/3600/24); } } Calendar 类 Calendar 的获取月份时的0对应1月, 7 对应8月 Calendar 获取的1对应的是 星期天, DAY_OF_WEEK add(int field, int amount) 给年月日时分秒增减 set(int field, int value) 给年月日时分秒设置数值 set(int year, int month, int date) 设置年月日 import java.text.SimpleDateFormat; import java.util.Calendar; public class Demo1_Calendar { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); String month = setTwoNu(cal.get(Calendar.MARCH) + 1); System.out.println(month); String week = getWeek(cal.get(Calendar.DAY_OF_WEEK)); System.out.println(week); System.out.println(cal.get(Calendar.DAY_OF_MONTH)); System.out.println(cal.getTime()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E"); System.out.println(sdf.format(cal.getTime())); } public static String getWeek(int week){ String [] strArray = {"", "星期日", "星期一","星期二","星期三","星期四","星期五","星期六"}; return strArray[week]; } public static String setTwoNu(int nu){ String s = String.valueOf(nu); if( nu <10 ){ s = "0" + nu; } return s; } } import java.util.Calendar; public class Demo2_Calendar { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 10); System.out.println(calendar.get(Calendar.YEAR)); System.out.println(calendar.get(Calendar.MONTH)); calendar.set(Calendar.MONTH, 10); System.out.println(calendar.get(Calendar.MONTH)); calendar.set(2021,9,01); System.out.println(calendar.get(Calendar.YEAR) +""+ (calendar.get(Calendar.MONTH)+1) +"" +calendar.get(Calendar.DAY_OF_MONTH)); } } Calendar 平年 润年 import java.util.Calendar; public class Demo3_Calendar { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); int year = 2020; calendar.set(year,2,1); calendar.add(Calendar.DAY_OF_MONTH, -1); System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); if( 29 == calendar.get(Calendar.DAY_OF_MONTH)){ System.out.println( year + "年是润年"); } else { System.out.println( year + "年是平年"); } } }

August 16, 2021&nbsp;·&nbsp;8 分钟&nbsp;·&nbsp;Lizicai