线程
线程基础
继承Thread
public class Demo {public static void main(String[] args) {new MyThread("线程A").start();new MyThread("线程B").start();new MyThread("线程C").start();}}class MyThread extends Thread {private String title;public MyThread(String title) {this.title = title;}public void run() {for (int i = 0; i < 10; i++) {System.out.println(title + ":" + i);}}}
实现Runnable
public class Demo {public static void main(String[] args) {new Thread(new MyThread("线程A")).start();new Thread(new MyThread("线程B")).start();new Thread(new MyThread("线程C")).start();}}class MyThread implements Runnable {private String title;public MyThread(String title) {this.title = title;}public void run() {for (int i = 0; i < 10; i++) {System.out.println(title + ":" + i);}}}
Lambda简写
public class Demo {public static void main(String[] args) {for(int j=0; j<3; j++) {String title = "线程" + j;new Thread(()->{for (int i = 0; i < 10; i++) {System.out.println(title + ":" + i);}}).start();}}}
实现Callable
import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;public class Demo {public static void main(String[] args) throws Exception {FutureTask<String> task = new FutureTask<String>(new MyThread());new Thread(task).start();System.out.println(task.get());}}class MyThread implements Callable<String> {public String call() throws Exception {for (int i = 0; i < 10; i++) {System.out.println("线程执行:" + i);}return "线程执行完成";}}
线程常用方法
获取线程名称
public class Demo {public static void main(String[] args) {new Thread(new MyThread(),"线程A").start();new Thread(new MyThread()).start();new Thread(new MyThread()).start();new Thread(new MyThread(),"线程B").start();}}class MyThread implements Runnable {public void run() {System.out.println(Thread.currentThread().getName());}}
线程休眠
public class Demo {public static void main(String[] args) {new Thread(new MyThread()).start();}}class MyThread implements Runnable {public void run() {System.out.println(Thread.currentThread().getName());try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("OK");}}
线程中断
public class Demo {public static void main(String[] args) throws Exception {Thread thread = new Thread(new MyThread());thread.start();Thread.sleep(1000);thread.interrupt();}}class MyThread implements Runnable {public void run() {try {System.out.println(Thread.currentThread().getName());Thread.sleep(3000);System.out.println("OK");} catch (InterruptedException e) {e.printStackTrace();}}}
强制执行
public class Demo {public static void main(String[] args) throws Exception {Thread mainThread = Thread.currentThread();new Thread(()-> {try {for(int i=0; i<20; i++) {if(i == 5) mainThread.join();Thread.sleep(100);System.out.println(Thread.currentThread().getName() + ":" + i);}} catch (InterruptedException e) {e.printStackTrace();}}).start();for(int i=0; i<20; i++) {Thread.sleep(100);System.out.println(Thread.currentThread().getName() + ":" + i);}}}
线程礼让
public class Demo {public static void main(String[] args) throws Exception {new Thread(()-> {try {for(int i=0; i<20; i++) {if(i%3 == 0) {Thread.yield();System.out.println("礼让");}Thread.sleep(100);System.out.println(Thread.currentThread().getName() + ":" + i);}} catch (InterruptedException e) {e.printStackTrace();}}).start();for(int i=0; i<20; i++) {Thread.sleep(100);System.out.println(Thread.currentThread().getName() + ":" + i);}}}
线程优先级
public class Demo {public static void main(String[] args) throws Exception {for(int j=0; j<3; j++) {Thread thread = new Thread(()-> {for(int i=0; i<100; i++) {System.out.println(Thread.currentThread().getName() + ":" + i);}});if(j == 2) {thread.setPriority(Thread.MAX_PRIORITY);}else {thread.setPriority(Thread.MIN_PRIORITY);}thread.start();}}}
同步
同步代码块
public class Demo {public static void main(String[] args) {MyThread myThread = new MyThread();new Thread(myThread).start();new Thread(myThread).start();new Thread(myThread).start();}}class MyThread implements Runnable {private int count = 10;public void run() {for (int i = 0; i < 10; i++) {try {synchronized (this) {Thread.sleep(100);if (count == 0) break;System.out.println(Thread.currentThread().getName() + ":" + count);count--;}} catch (InterruptedException e) {e.printStackTrace();}}}}
同步方法
public class Demo {public static void main(String[] args) {MyThread myThread = new MyThread();new Thread(myThread).start();new Thread(myThread).start();new Thread(myThread).start();}}class MyThread implements Runnable {private int count = 10;private synchronized boolean fun() {try {Thread.sleep(100);if (count == 0) return true;System.out.println(Thread.currentThread().getName() + ":" + count);count--;} catch (InterruptedException e) {e.printStackTrace();}return false;}public void run() {for (int i = 0; i < 10; i++) {if(fun()) break;}}}
死锁
public class Demo implements Runnable {private Jian jian = new Jian();private Qiang qiang = new Qiang();public static void main(String[] args) {new Demo();}public void run() {jian.say(qiang);}public Demo() {new Thread(this).start();qiang.say(jian);}}class Jian {public synchronized void say(Qiang qiang) {System.out.println("Jian要过去");qiang.get();}public synchronized void get() {System.out.println("Jian过去了");}}class Qiang {public synchronized void say(Jian jian) {System.out.println("Qiang要过去");jian.get();}public synchronized void get() {System.out.println("Qiang过去了");}}
生产者消费者
public class Demo {public static void main(String[] args) {Meaasge meaasge = new Meaasge();for (int i = 1; i <= 3; i++) {new Thread(new Consumer(meaasge), "Consumer" + i).start();}for (int i = 1; i <= 3; i++) {new Thread(new Producer(meaasge), "Producer" + i).start();}}}// 消息class Meaasge {private String contents;private boolean available = false;public synchronized void get() {while (available == false) {try {wait();} catch (InterruptedException e) {}}available = false;System.out.println(Thread.currentThread().getName() + "消费:" + contents);notifyAll();}public synchronized void put(String value) {while (available == true) {try {wait();} catch (InterruptedException e) {}}contents = value;available = true;System.out.println(Thread.currentThread().getName() + "生产:" + contents);notifyAll();}}// 消费者class Consumer implements Runnable {private Meaasge meaasge;public Consumer(Meaasge meaasge) {this.meaasge = meaasge;}public void run() {for (int i = 0; i < 5; i++) {meaasge.get();}}}// 生产者class Producer implements Runnable {private Meaasge meaasge;public Producer(Meaasge meaasge) {this.meaasge = meaasge;}public void run() {for (int i = 0; i < 5; i++) {meaasge.put(String.valueOf(Math.random()));try {Thread.sleep((int) (Math.random() * 500));} catch (Exception e) {}}}}
停止线程
public class Demo {private static boolean flag = true;public static void main(String[] args) throws Exception {new Thread(new Runnable() {public void run() {while (flag) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Math.random());}}}, "执行线程").start();Thread.sleep(4000);flag = false;}}
守护线程
public class Demo {public static void main(String[] args) throws Exception {Thread userThread = new Thread(new Runnable() {public void run() {for (int i = 0; i < 10; i++) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + i);}}}, "用户线程");Thread daemonThread = new Thread(new Runnable() {public void run() {for (int i = 0; i < 100; i++) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + i);}}}, "守护线程");daemonThread.setDaemon(true);daemonThread.start();userThread.start();}}
volatile关键字
public class Demo {public static void main(String[] args) throws Exception {MyThread myThread = new MyThread();new Thread(myThread, "卖票线程A:").start();new Thread(myThread, "卖票线程B:").start();new Thread(myThread, "卖票线程C:").start();new Thread(myThread, "卖票线程D:").start();new Thread(myThread, "卖票线程E:").start();}}class MyThread implements Runnable {// volatile表示直接操作内存,不用拷贝数据计算后再赋值回去,它没有synchronized的功能private volatile int ticket = 5;public void run() {synchronized (this) {if (ticket > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + ticket);ticket--;}}}}
基础类库
字符串
public class Demo {public static void main(String[] args) throws Exception {// 字符串String str = "Hello" + "World" + 12345;System.out.println(str);// 线程安全的StringBuffer buffer = new StringBuffer();buffer.append("Hello");buffer.append("World");buffer.append(12345);System.out.println(buffer);// 线程不安全StringBuilder builder = new StringBuilder();builder.append("Hello");builder.append("World");builder.append(12345);System.out.println(builder);}}
字符序列
public class Demo {public static void main(String[] args) throws Exception {String str = "Hello" + "World" + 12345;print(str);StringBuffer buffer = new StringBuffer();buffer.append("Hello");buffer.append("World");buffer.append(12345);print(buffer);StringBuilder builder = new StringBuilder();builder.append("Hello");builder.append("World");builder.append(12345);print(builder);}public static void print(CharSequence sequence) {System.out.println(sequence);}}
自动关闭
public class Demo {public static void main(String[] args) throws Exception {try (Message message = new MyMessage()) {message.send();} catch (Exception e) {e.printStackTrace();}}}interface Message extends AutoCloseable {public void send();}class MyMessage implements Message {public void close() throws Exception {System.out.println("关闭通道");}public void send() {System.out.println("发送消息");}}
运行时(Runtime)
public class Demo {public static void main(String[] args) throws Exception {Runtime runtime = Runtime.getRuntime();System.out.println("CPU核数:" + runtime.availableProcessors());memory(runtime);String str = "";for(int i=0; i<50000; i++) {str += i + "";}System.out.println("字符串长度:" + str.length());memory(runtime);runtime.gc();Thread.sleep(1000);memory(runtime);}private static void memory(Runtime runtime) {System.out.println("------------------------------");System.out.println("最大内存:" + toGB(runtime.maxMemory()));System.out.println("总内存:" + toGB(runtime.totalMemory()));System.out.println("可以内存:" + toGB(runtime.freeMemory()));}private static String toGB(long size) {return Math.floor(size / 1.0 / 1024 / 1024 / 1024 * 100) / 100 + "GB";}}
系统(System)
public class Demo {public static void main(String[] args) throws Exception {long start = System.currentTimeMillis();{String str = "";for(int i=0; i<1000; i++) {str += i + "";}System.out.println("字符串长度:" + str.length());}System.gc();long end = System.currentTimeMillis();System.out.println("操作耗时:" + (end-start));}}
public class Demo {public static void main(String[] args) throws Exception {// 打印所有Propertie的简单方法System.getProperties().list(System.out);}}
清理(Cleaner)
import java.lang.ref.Cleaner;public class Demo {public static void main(String[] args) {try(MemberCleaning memberCleaning = new MemberCleaning()) {System.out.println(memberCleaning);}catch(Exception e) {e.printStackTrace();}}}class Member implements Runnable {public Member() {System.out.println("创建");}public void run() {System.out.println("销毁");}}// Java9以上版本支持class MemberCleaning implements AutoCloseable {private Member member;private Cleaner.Cleanable cleanable;private static final Cleaner CLEANER = Cleaner.create();public MemberCleaning() {this.member = new Member();this.cleanable = CLEANER.register(this, this.member);}public void close() throws Exception {this.cleanable.clean();}}
克隆
public class Demo {public static void main(String[] args) throws Exception {Member member1 = new Member("张三", 18);Member member2 = member1.clone();System.out.println(member1);System.out.println(member2);}}class Member implements Cloneable {private String name;private int age;public Member(String name, int age) {this.name = name;this.age = age;}public String toString() {return super.toString() + " [name=" + name + ", age=" + age + "]";}protected Member clone() throws CloneNotSupportedException {return (Member) super.clone();}}
数字操作类
数学计算
public class Demo {public static void main(String[] args) throws Exception {System.out.println(Math.abs(-7));System.out.println(Math.max(8, 20));System.out.println(Math.random());System.out.println(Math.round(3.14159));System.out.println(myRound(3.14159, 2));System.out.println(myRound(3.14159, 3));}// 自定义保留N位小数的四舍五入public static double myRound(double num, int scale) {return Math.round(num * Math.pow(10,scale)) / Math.pow(10,scale);}}
随机数
import java.util.Random;public class Demo {public static void main(String[] args) throws Exception {Random random = new Random();System.out.println(random.nextBoolean());System.out.println(random.nextDouble());for(int i=0; i<10; i++) {System.out.print(random.nextInt(100) + "、");}}}
大数处理
import java.math.BigDecimal;import java.math.BigInteger;public class Demo {public static void main(String[] args) throws Exception {BigInteger num1 = new BigInteger("2353464378658920397684376893768957828937529487543897698389376935");BigInteger num2 = new BigInteger("83957928375247");System.out.println("加法:" + num1.add(num2));System.out.println("减法:" + num1.subtract(num2));System.out.println("乘法:" + num1.multiply(num2));System.out.println("除法:" + num1.divide(num2));BigInteger[] result = num1.divideAndRemainder(num2);System.out.println("商:" + result[0]);System.out.println("余数:" + result[1]);BigDecimal num3 = new BigDecimal("3.141596976431634531351035435456465431315465465465465456465465464654654");BigDecimal num4 = new BigDecimal("654646.321654");System.out.println(num3.add(num4));}}
日期操作
日期类
import java.util.Date;public class Demo {public static void main(String[] args) throws Exception {Date date = new Date();System.out.println(date.getTime());System.out.println(new Date());System.out.println(new Date(System.currentTimeMillis()));}}
日期格式化
import java.text.SimpleDateFormat;import java.util.Date;public class Demo {public static void main(String[] args) throws Exception {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");// 日期转字符串System.out.println(sdf.format(date));// 字符串转日期date = sdf.parse("2021-05-15 15:16:41.337");System.out.println(date);}}
开发支持
正则表达式
import java.util.Arrays;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Demo {public static void main(String[] args) {System.out.println("123456".matches("\\d+"));System.out.println("a".matches("[abc]"));System.out.println("d".matches("[^abc]"));System.out.println("F".matches("[a-zA-Z]"));System.out.println("5".matches("[0-9]"));System.out.println("3.14159".matches("\\d+(\\.\\d+)?"));System.out.println("hg2341@jgjh67^hvh^&*(434jhbj^jbsf)*!mbh".replaceAll("\\W", ""));System.out.println(Arrays.toString("a65876d987987f888g987987s78789".split("\\d+")));String str = "INSERT INTO user(id,username,password) VALUES (#{id},#{username},#{password})";String regex = "#\\{\\w+\\}";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(str);while(matcher.find()) {System.out.println(matcher.group(0));}}}
国际化
i18n.properties
info=Himsg=Hi {0} , Welcome to {1}
i18n_en_US.properties
info=Hellomsg=Hello {0} , Welcome to {1}
i18n_zh_CN.properties
info=Ni Haomsg=Ni Hao {0} , Huan ying lai dao {1}
import java.text.MessageFormat;import java.util.Locale;import java.util.ResourceBundle;public class Demo {public static void main(String[] args) {Locale locale = new Locale("zh", "CN");ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);System.out.println(bundle.getString("info"));String str = MessageFormat.format(bundle.getString("msg"), "张三", "三亚");System.out.println(str);}}
UUID
import java.util.UUID;public class Demo {public static void main(String[] args) {System.out.println(UUID.randomUUID().toString());}}
Optional
import java.util.Optional;public class Demo {public static void main(String[] args) throws Exception {System.out.println(getCarInsuranceName1(null));System.out.println(getCarInsuranceName2(null));}public static String getCarInsuranceName1(Person person) {if(person != null) {Car car = person.getCar();if(car != null) {Insurance insurance = car.getInsurance();if(insurance != null) {return insurance.getName();}}}return "Unknown";}public static String getCarInsuranceName2(Person person) {return Optional.ofNullable(person).map(Person::getCar).map(Car::getInsurance).map(Insurance::getName).orElse("Unknown");}}class Person {private Car car;public Car getCar() {return car;}}class Car {private Insurance insurance;public Insurance getInsurance() {return insurance;}}class Insurance {private String name;public String getName() {return name;}}
ThreadLocal
public class Demo {public static void main(String[] args) throws Exception {new Thread(new Runnable() {public void run() {Message message = new Message();message.setInfo("AAAAA");Channel.setMessage(message);Channel.send();}}, "线程A").start();new Thread(new Runnable() {public void run() {Message message = new Message();message.setInfo("BBBBB");Channel.setMessage(message);Channel.send();}}, "线程B").start();new Thread(new Runnable() {public void run() {Message message = new Message();message.setInfo("CCCCC");Channel.setMessage(message);Channel.send();}}, "线程C").start();}}class Channel {private static final ThreadLocal<Message> THREAD_LOCAL = new ThreadLocal<Message>();private Channel() { }public static void setMessage(Message message) {THREAD_LOCAL.set(message);}public static void send() {System.out.println(Thread.currentThread().getName() + "发送消息:" + THREAD_LOCAL.get().getInfo());}}class Message {private String info;public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}}
定时调度
import java.util.Timer;import java.util.TimerTask;public class Demo {public static void main(String[] args) throws Exception {Timer timer = new Timer();// timer.schedule(new MyTask(), 0);timer.scheduleAtFixedRate(new MyTask(), 100, 1000);}}class MyTask extends TimerTask {public void run() {System.out.println(Thread.currentThread().getName() + "执行了");}}
Base64加密和解密
import java.util.Base64;public class Demo {public static void main(String[] args) throws Exception {String str = "Hello 世界!";String msg = new String(Base64.getEncoder().encode(str.getBytes()));System.out.println("加密:" + msg);String oldStr = new String(Base64.getDecoder().decode(msg.getBytes()));System.out.println("解密:" + oldStr);System.out.println("-----------------------------------");String result1 = encode(str);String result2 = decode(result1);System.out.println("自定义加密:" + result1);System.out.println("自定义解密:" + result2);}// 自定义加密public static String encode(String str) {str = "盐值123" + str;byte[] bytes = str.getBytes();for(int i=0; i<3; i++) {bytes = Base64.getEncoder().encode(bytes);}return new String(bytes);}// 自定义解密public static String decode(String str) {byte[] bytes = str.getBytes();for(int i=0; i<3; i++) {bytes = Base64.getDecoder().decode(bytes);}return new String(bytes).replaceFirst("盐值123", "");}}
对象排序
import java.util.Arrays;public class Demo {public static void main(String[] args) {Person[] persons = new Person[3];persons[0] = new Person("张三A", 18);persons[1] = new Person("张三B", 18);persons[2] = new Person("张三C", 16);Arrays.sort(persons);for (Person person : persons) {System.out.println(person);}}}class Person implements Comparable<Person> {private String name;private Integer age;public Person(String name, Integer age) {super();this.name = name;this.age = age;}public String toString() {return "Person [name=" + name + ", age=" + age + "]";}public int compareTo(Person person) {int result = age.compareTo(person.age);return result==0 ? name.compareTo(person.name) : result;}}
案例:生成字符串(A-Z)
public class Demo {public static void main(String[] args) {StringBuffer buffer = new StringBuffer();for(int i='A'; i<='Z'; i++) {buffer.append((char)i);}System.out.println(buffer);}}
IO操作
文件操作类
import java.io.File;import java.util.Date;public class Demo {public static void main(String[] args) throws Exception {File file = new File("AA/BB/CC/DDD.txt");if(!file.exists()) {System.out.println("文件不存在");File parent = file.getParentFile();if(!parent.exists()) {System.out.println("父目录不存在,开始创建父目录:" + parent.mkdirs());}else {System.out.println("父目录存在");}System.out.println("创建文件:" + file.createNewFile());}else {System.out.println("文件已存在");}System.out.println("文件绝对路径:" + file.getAbsolutePath());System.out.println("文件名称:" + file.getName());System.out.println("文件大小字节数:" + file.length());System.out.println("文件最后修改时间:" + new Date(file.lastModified()));System.out.println("文件是否可读:" + file.canRead());System.out.println("文件是否可写:" + file.canWrite());System.out.println("是否是文件夹:" + file.isDirectory());System.out.println("删除文件:" + file.delete());File aa = file.getParentFile().getParentFile().getParentFile();System.out.println("列文件夹:");File[] files = aa.listFiles();for (File file2 : files) {System.out.println(file2.getName());}}}
写字节数据到文件
import java.io.File;import java.io.FileOutputStream;public class Demo {public static void main(String[] args) throws Exception {File file = new File("text.txt");try (FileOutputStream out = new FileOutputStream(file)) {out.write("1 Hello World!!!\r\n".getBytes());out.write("2 Hello World!!!\r\n".getBytes());out.write("3 Hello World!!!\r\n".getBytes());out.flush();} catch (Exception e) {e.printStackTrace();}System.out.println(file.getAbsolutePath());}}
从文件读取字节数据
import java.io.File;import java.io.FileInputStream;import java.io.InputStream;public class Demo {public static void main(String[] args) throws Exception {File file = new File("text.txt");InputStream in = new FileInputStream(file);byte[] buf = new byte[1024];int len = in.read(buf);in.close();String str = new String(buf, 0, len);System.out.println(str);}}
写字符数据到文件
import java.io.File;import java.io.FileWriter;import java.io.Writer;public class Demo {public static void main(String[] args) throws Exception {File file = new File("text.txt");Writer writer = new FileWriter(file);writer.write("AAAAAAA");writer.write("BBBBBBB");writer.write("\r\n");writer.append("CCCCCC");writer.append("DDDDDD");writer.flush();writer.close();System.out.println(file.getAbsolutePath());}}
从文件读取字符数据
import java.io.File;import java.io.FileReader;import java.io.Reader;public class Demo {public static void main(String[] args) throws Exception {File file = new File("text.txt");Reader reader = new FileReader(file);char[] cbuf = new char[1024];int len = reader.read(cbuf);reader.close();String str = new String(cbuf, 0, len);System.out.println(str);}}
转换流
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;public class Demo {public static void main(String[] args) throws Exception {File file = new File("text.txt");// 写文件FileOutputStream out = new FileOutputStream(file);OutputStreamWriter writer = new OutputStreamWriter(out);writer.write("AAA\r\n");writer.write("BBB\r\n");writer.write("CCC\r\n");writer.flush();writer.close();// 读文件FileInputStream in = new FileInputStream(file);InputStreamReader reader = new InputStreamReader(in);char[] cbuf = new char[1024];int len = reader.read(cbuf);reader.close();String str = new String(cbuf, 0, len);System.out.println(str);}}
文件夹拷贝
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;public class Demo {public static void main(String[] args) throws Exception {File folder = new File(System.getenv("JAVA_HOME"));if(folder.exists() && folder.isDirectory()) {File dest = new File("复制");if(!dest.exists()) dest.mkdir();if(dest.isDirectory()) copyFolder(folder, dest);}System.out.println("OK");}// 复制文件夹private static void copyFolder(File from, File to) throws Exception {File[] files = from.listFiles();for (File file : files) {if(file.isDirectory()) {File fromFile = file;File toFile = new File(to, fromFile.getName());toFile.mkdir();copyFolder(fromFile, toFile);}else {File fromFile = file;File toFile = new File(to, fromFile.getName());FileInputStream in = new FileInputStream(fromFile);FileOutputStream out = new FileOutputStream(toFile);byte[] buf = new byte[2048];int len = -1;while((len=in.read(buf)) != -1) {out.write(buf, 0, len);}out.flush();out.close();in.close();System.out.println(toFile.getAbsolutePath());}}}}
内存流
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.CharArrayReader;import java.io.CharArrayWriter;public class Demo {public static void main(String[] args) throws Exception {int data = -1;String str = "www.baidu.com";// 字节内存流ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes());ByteArrayOutputStream out = new ByteArrayOutputStream();while((data=in.read()) != -1) {out.write(Character.toUpperCase(data));}System.out.println(out.toString());out.close();in.close();// 字符内存流CharArrayReader reader = new CharArrayReader(str.toCharArray());CharArrayWriter writer = new CharArrayWriter();while((data=reader.read()) != -1) {writer.write(Character.toUpperCase(data));}System.out.println(writer.toString());writer.close();reader.close();}}
管道流
import java.io.PipedInputStream;import java.io.PipedOutputStream;// 字节管道流public class Demo {public static void main(String[] args) throws Exception {SendThread sendThread = new SendThread();ReceiveThread receiveThread = new ReceiveThread();sendThread.getOutput().connect(receiveThread.getInput());new Thread(sendThread).start();new Thread(receiveThread).start();}}class SendThread implements Runnable {private PipedOutputStream out = new PipedOutputStream();public void run() {try {for(int i=0; i<10; i++) {String temp = "Hello" + i;out.write(temp.getBytes());System.out.println("发送:" + temp);}out.close();} catch (Exception e) {e.printStackTrace();} finally {System.out.println("发送线程结束");}}public PipedOutputStream getOutput() {return out;}}class ReceiveThread implements Runnable {private PipedInputStream in = new PipedInputStream();public void run() {try {int len = -1;byte[] buf = new byte[6];while((len=in.read(buf)) != -1) {Thread.sleep(500);System.out.println("接收:" + new String(buf, 0, len));}in.close();} catch (Exception e) {e.printStackTrace();} finally {System.out.println("接收线程结束");}}public PipedInputStream getInput() {return in;}}
import java.io.PipedReader;import java.io.PipedWriter;// 字符管道流public class Demo {public static void main(String[] args) throws Exception {SendThread sendThread = new SendThread();ReceiveThread receiveThread = new ReceiveThread();sendThread.getWrite().connect(receiveThread.getReader());new Thread(sendThread).start();new Thread(receiveThread).start();}}class SendThread implements Runnable {private PipedWriter writer = new PipedWriter();public void run() {try {for(int i=0; i<10; i++) {String temp = "Hello" + i;writer.write(temp);System.out.println("发送:" + temp);}writer.close();} catch (Exception e) {e.printStackTrace();} finally {System.out.println("发送线程结束");}}public PipedWriter getWrite() {return writer;}}class ReceiveThread implements Runnable {private PipedReader reader = new PipedReader();public void run() {try {int len = -1;char[] buf = new char[6];while((len=reader.read(buf)) != -1) {Thread.sleep(500);System.out.println("接收:" + new String(buf, 0, len));}reader.close();} catch (Exception e) {e.printStackTrace();} finally {System.out.println("接收线程结束");}}public PipedReader getReader() {return reader;}}
随机访问文件
import java.io.File;import java.io.FileWriter;import java.io.RandomAccessFile;public class Demo {public static void main(String[] args) throws Exception {File file = new File("test.txt");// 测试数据准备FileWriter writer = new FileWriter(file);writer.write("AAAAA");writer.write("BBBBB");writer.write("CCCCC");writer.write("DDDDD");writer.close();// 随机访问文件RandomAccessFile raf = new RandomAccessFile(file, "rw");// 跳过15个字节raf.skipBytes(15);// 读5个字节byte[] buf = new byte[5];int len = raf.read(buf);System.out.println(new String(buf, 0, len));// 回退10个字节raf.seek(10);// 再读5个字节len = raf.read(buf);System.out.println(new String(buf, 0, len));// 关闭raf.close();}}
缓冲流
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;public class Demo {public static void main(String[] args) throws Exception {File file = new File("test.txt");// 字节缓冲流BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));out.write("AAAA\r\n".getBytes());out.write("BBBB\r\n".getBytes());out.write("CCCC\r\n".getBytes());out.close();BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));byte[] buf = new byte[1024];int len = in.read(buf);System.out.println(new String(buf, 0, len));in.close();// 字符缓冲流BufferedWriter writer = new BufferedWriter(new FileWriter(file));writer.write("AAAA\r\n");writer.write("BBBB\r\n");writer.write("CCCC\r\n");writer.close();BufferedReader reader = new BufferedReader(new FileReader(file));System.out.println(reader.readLine());System.out.println(reader.readLine());System.out.println(reader.readLine());reader.close();}}
输入输出
打印流
import java.io.File;import java.io.FileOutputStream;import java.io.PrintStream;public class Demo {public static void main(String[] args) throws Exception {File file = new File("test.txt");PrintStream stream = new PrintStream(new FileOutputStream(file));stream.print(true);stream.print('A');stream.print("Hello");stream.printf("姓名:%s,年龄:%d", "张三", 18);stream.close();System.out.println("OK");}}
System对输入输出的支持
import java.io.InputStream;public class Demo {public static void main(String[] args) {try {InputStream in = System.in;System.out.print("请随便输入数据:");byte[] buf = new byte[10];int len = in.read(buf);System.out.println(new String(buf, 0, len));System.out.println(10/0);} catch (Exception e) {System.out.println(e.getMessage());System.err.println(e.getMessage());}}}
扫描流
import java.io.File;import java.io.PrintStream;import java.util.Scanner;public class Demo {public static void main(String[] args) throws Exception {// 键盘输入Scanner scanner = new Scanner(System.in);System.out.print("输入数字:");long num = scanner.nextLong();System.out.println("你输入了:" + num);System.out.print("输入字符串:");String str = scanner.next();System.out.println("你输入了:" + str);scanner.close();// 写数据File file = new File("test.txt");PrintStream stream = new PrintStream(file);stream.print("AA AAA\r\n");stream.print("BB BBB\r\n");stream.print("CC CCC\r\n");stream.close();// 读数据scanner = new Scanner(file);scanner.useDelimiter("\r\n");while(scanner.hasNext()) {System.out.println(scanner.next());}scanner.close();}}
序列化
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class Demo {private static File file = new File("test.txt");public static void main(String[] args) throws Exception {Person person = new Person("张三", 18, '男');saveObject(person);System.out.println(loadObject());}// 序列化private static void saveObject(Object obj) throws Exception {ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));out.writeObject(obj);out.close();}// 反序列化private static Object loadObject() throws Exception {ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));Object obj = in.readObject();in.close();return obj;}}@SuppressWarnings("serial")class Person implements Serializable {private String name;private int age;// 此属性不会被序列化private transient char sex;public Person(String name, int age, char sex) {super();this.name = name;this.age = age;this.sex = sex;}public String toString() {return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";}}
反射
Class类对象的3种实例化方式
import java.util.Date;public class Demo {public static void main(String[] args) throws Exception {Class<?> class1 = new Date().getClass();Class<?> class2 = Date.class;Class<?> class3 = Class.forName("java.util.Date");System.out.println(class1);System.out.println(class2);System.out.println(class3);}}
反射实例化对象
public class Demo {public static void main(String[] args) throws Exception {Class<?> cls = Class.forName("Person");Object object = cls.newInstance();// JDK1.9以后上面的方法标记为过时,下面是替换的方法// Object object = cls.getDeclaredConstructor().newInstance();System.out.println(object);}}class Person {public Person() {System.out.println("调用了无参构造方法");}public String toString() {return "调用了toString方法";}}
反射与工厂设计模式
// 客户端public class Demo {public static void main(String[] args) throws Exception {Food food = null;food = Factory.getInstance("Bread", Bread.class);food.eat();food = Factory.getInstance("Rice", Rice.class);food.eat();Water water = null;water = Factory.getInstance("Cola", Cola.class);water.drink();water = Factory.getInstance("Sprite", Sprite.class);water.drink();}}// 食物接口interface Food {public void eat();}// 面包实现class Bread implements Food {public void eat() {System.out.println("吃面包");}}// 米饭实现class Rice implements Food {public void eat() {System.out.println("吃米饭");}}// 水接口interface Water {public void drink();}// 可乐实现class Cola implements Water {public void drink() {System.out.println("喝可乐");}}// 雪碧实现class Sprite implements Water {public void drink() {System.out.println("喝雪碧");}}// 工厂class Factory {@SuppressWarnings("unchecked")public static <T> T getInstance(String className, Class<T> clazz) throws Exception {Class<?> cls = Class.forName(className);Object object = cls.newInstance();return (T) object;}}
反射与单例懒汉式
public class Demo {public static void main(String[] args) {for (int i = 0; i < 3; i++) {new Thread(() -> {Massage.getInstance().fun();}, "线程" + i).start();}}}// 单例:懒汉式class Massage {private static volatile Massage massage;private Massage() {System.out.println("调用了构造方法");}public static Massage getInstance() {if (massage == null) {synchronized (Massage.class) {if (massage == null) {massage = new Massage();}}}return massage;}public void fun() {System.out.println("AAA");}}
反射获取类结构信息
public class Demo {public static void main(String[] args) {Class<?> cls = String.class;System.out.println("获取包:" + cls.getPackage());System.out.println("获取父类:" + cls.getSuperclass());System.out.println("获取接口:");Class<?>[] interfaces = cls.getInterfaces();for (Class<?> clazz : interfaces) {System.out.println(clazz);}}}
反射调用构造方法
import java.lang.reflect.Constructor;import java.util.Date;public class Demo {public static void main(String[] args) throws Exception {Class<?> cls = Date.class;Constructor<?> constructor = cls.getConstructor(long.class);Object obj = constructor.newInstance(System.currentTimeMillis());System.out.println(obj);}}
反射调用普通方法
import java.lang.reflect.Method;public class Demo {public static void main(String[] args) throws Exception {Class<?> cls = Class.forName("Person");Object object = cls.newInstance();Method setMethod = cls.getDeclaredMethod("setName", String.class);setMethod.invoke(object, "张三");Method getMethod = cls.getDeclaredMethod("getName");System.out.println(getMethod.invoke(object));}}class Person {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}
反射调用成员
import java.lang.reflect.Field;public class Demo {public static void main(String[] args) throws Exception {Class<?> cls = Class.forName("Person");Object object = cls.newInstance();// 调用public成员Field name = cls.getDeclaredField("name");System.out.println(name.getType());name.set(object, "张三");System.out.println(name.get(object));// 调用private成员Field age = cls.getDeclaredField("age");age.setAccessible(true);System.out.println(age.getType());age.set(object, 18);System.out.println(age.get(object));}}class Person {public String name;private int age;}
Unsafe工具类
import java.lang.reflect.Field;import sun.misc.Unsafe;public class Demo {public static void main(String[] args) throws Exception {Field field = Unsafe.class.getDeclaredField("theUnsafe");field.setAccessible(true);Unsafe unsafe = (Unsafe) field.get(null);// 利用Unsafe类绕过了JVM的管理机制,可以在没有实例化对象的情况下获取Singleton类的实例化对象Singleton singleton = (Singleton) unsafe.allocateInstance(Singleton.class);singleton.print();}}class Singleton {private Singleton() {System.out.println("执行构造方法");}public void print() {System.out.println("执行print方法");}}
反射与简单Java类
import java.lang.reflect.Field;import java.text.SimpleDateFormat;import java.util.Date;public class Demo {public static void main(String[] args) throws Exception {// 人Class<?> personClass = Class.forName("Person");Object person = personClass.newInstance();Field nameField = personClass.getDeclaredField("name");Field ageField = personClass.getDeclaredField("age");Field computerField = personClass.getDeclaredField("computer");personClass.getDeclaredMethod(toSetMethodName(nameField.getName()), nameField.getType()).invoke(person, "张三");personClass.getDeclaredMethod(toSetMethodName(ageField.getName()), ageField.getType()).invoke(person, Integer.parseInt("18"));// 计算机Class<?> computerClass = computerField.getType();Object computer = computerClass.newInstance();Field brandField = computerClass.getDeclaredField("brand");Field spaceField = computerClass.getDeclaredField("space");Field priceField = computerClass.getDeclaredField("price");Field dateField = computerClass.getDeclaredField("date");computerClass.getDeclaredMethod(toSetMethodName(brandField.getName()), brandField.getType()).invoke(computer, "华为");computerClass.getDeclaredMethod(toSetMethodName(spaceField.getName()), spaceField.getType()).invoke(computer, Long.valueOf("5120000000"));computerClass.getDeclaredMethod(toSetMethodName(priceField.getName()), priceField.getType()).invoke(computer, Double.parseDouble("7599.99"));computerClass.getDeclaredMethod(toSetMethodName(dateField.getName()), dateField.getType()).invoke(computer, new SimpleDateFormat("yyyy-MM-dd").parse("2021-05-20"));// 人有计算机personClass.getDeclaredMethod(toSetMethodName(computerField.getName()), computerClass).invoke(person, computer);// 打印对象System.out.println(person);}// 根据属性名称拼接setXXX方法名称public static String toSetMethodName(String key) {return "set" + Character.toUpperCase(key.charAt(0)) + key.substring(1);}}// 计算机class Computer {private String brand;private Long space;private double price;private Date date;public void setBrand(String brand) {this.brand = brand;}public void setSpace(Long space) {this.space = space;}public void setPrice(double price) {this.price = price;}public void setDate(Date date) {this.date = date;}public String toString() {return "Computer [brand=" + brand + ", space=" + space + ", price=" + price + ", date=" + date + "]";}}// 人class Person {private String name;private int age;private Computer computer;public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public void setComputer(Computer computer) {this.computer = computer;}public String toString() {return "Person [name=" + name + ", age=" + age + ", computer=" + computer + "]";}}
自定义ClassLoader
public class Message {public void send(String msg) {System.out.println("发送消息:" + msg);}}
import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.lang.reflect.Method;public class Demo {public static void main(String[] args) throws Exception {MyClassLoader myClassLoader = new MyClassLoader();Class<?> clazz = myClassLoader.loadData("E:/Message.class", "Message");Object object = clazz.newInstance();Method method = clazz.getDeclaredMethod("send", String.class);method.invoke(object, "你好");}}class MyClassLoader extends ClassLoader {public Class<?> loadData(String filePath, String className) throws IOException {int len = -1;byte[] buf = new byte[1024];File file = new File(filePath);FileInputStream in = new FileInputStream(file);ByteArrayOutputStream out = new ByteArrayOutputStream();while((len=in.read(buf)) != -1) {out.write(buf, 0, len);}out.flush();out.close();in.close();byte[] data = out.toByteArray();return defineClass(className, data, 0, data.length);}}
动态代理设计模式
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;// 客户端public class Demo {public static void main(String[] args) {Food food = (Food) new FoodProxy().bind(new Bread());food.eat();}}// 食物接口interface Food {public void eat();}// 面包实现class Bread implements Food {public void eat() {System.out.println("吃面包");}}// 食物代理class FoodProxy implements InvocationHandler {private Object target;public Object bind(Object target) {this.target = target;return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("吃之前处理");Object result = method.invoke(target, args);System.out.println("吃之后处理");return result;}}
CGLib实现代理设计模式
<dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>3.3.0</version></dependency>
import java.lang.reflect.Method;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;// 客户端public class Demo {public static void main(String[] args) {Bread bread = new Bread();Enhancer enhancer = new Enhancer();enhancer.setSuperclass(bread.getClass());enhancer.setCallback(new BreadProxy(bread));Bread bread2 = (Bread) enhancer.create();bread2.eat();}}// 面包class Bread {public void eat() {System.out.println("吃面包");}}// 面包代理class BreadProxy implements MethodInterceptor {private Object target;public BreadProxy(Object target) {this.target = target;}public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {System.out.println("吃之前处理");Object result = method.invoke(target, args);System.out.println("吃之后处理");return result;}}
获取Annotation信息
import java.io.Serializable;import java.lang.annotation.Annotation;public class Demo {public static void main(String[] args) throws Exception {print(Message.class.getAnnotations());print(MessageImpl.class.getAnnotations());print(MessageImpl.class.getDeclaredMethod("send").getAnnotations());}public static void print(Annotation[] annotations) {System.out.println("------------------------");for (Annotation annotation : annotations) {System.out.println(annotation);}}}@FunctionalInterface//RetentionPolicy.RUNTIME@Deprecated//RetentionPolicy.RUNTIMEinterface Message {public void send();}@SuppressWarnings("serial")//RetentionPolicy.SOURCEclass MessageImpl implements Message, Serializable {@Override//RetentionPolicy.SOURCEpublic void send() {System.out.println("发送消息");}}
自定义Annotation
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method;public class Demo {public static void main(String[] args) throws Exception {Class<?> clazz = Message.class;Method method = clazz.getMethod("send", String.class);MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);String msg = annotation.title() + "-" + annotation.url();method.invoke(clazz.newInstance(), msg);}}@Retention(RetentionPolicy.RUNTIME)@interface MyAnnotation {public String title();public String url() default "www.baidu.com";}class Message {@MyAnnotation(title = "百度")public void send(String msg) {System.out.println("发送消息:" + msg);}}
代理、工厂、Annotation整合
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;// 客户端public class Demo {public static void main(String[] args) throws Exception {MessageService messageService = new MessageService();messageService.send("Hello");}}// 消息接口interface Message {public void send(String msg);}// 消息实现1class MessageImpl implements Message {public void send(String msg) {System.out.println("发送消息:" + msg);}}// 消息实现2class NetMessageImpl implements Message {public void send(String msg) {System.out.println("网络发送消息:" + msg);}}// 消息代理class MessageProxy implements InvocationHandler {private Object target;public Object bind(Object target) {this.target = target;return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("发送前处理");Object result = method.invoke(target, args);System.out.println("发送后处理");return result;}}// 消息工厂class Factory {private Factory() { }@SuppressWarnings("unchecked")public static <T> T getInstance(Class<?> clazz) throws Exception {return (T) new MessageProxy().bind(clazz.newInstance());}}// 消息注解@Retention(RetentionPolicy.RUNTIME)@interface UseMessage {public Class<?> clazz();}// 消息服务//@UseMessage(clazz = MessageImpl.class)@UseMessage(clazz = NetMessageImpl.class)class MessageService {private Message message;public MessageService() throws Exception {UseMessage annotation = MessageService.class.getAnnotation(UseMessage.class);message = Factory.getInstance(annotation.clazz());}public void send(String msg) {message.send(msg);}}
集合
List
List新支持
import java.util.List;public class Demo {public static void main(String[] args) throws Exception {// JDK9List<String> list = List.of("Hello","World","你好","世界");System.out.println(list);}}
ArrayList
- ArrayList 是一个可改变大小的数组.当更多的元素加入到ArrayList中时,其大小将会动态地增长.内部的元素可以直接通过get与set方法进行访问,因为ArrayList本质上就是一个数组
- 默认情况下ArrayList的初始容量非常小,所以如果可以预估数据量的话,分配一个较大的初始值属于最佳实践,这样可以减少调整大小的开销 ```java import java.util.ArrayList; import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
List
System.out.println();List<Person> persons = new ArrayList<Person>();persons.add(new Person("张三", 18));persons.add(new Person("李四", 19));persons.add(new Person("小强", 20));persons.remove(new Person("小强", 20));persons.forEach(System.out::println);}
} class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String toString() { return “Person [name=” + name + “, age=” + age + “]”; } }
<a name="jrHDq"></a>#### LinkedList- LinkedList 是一个双链表,在添加和删除元素时具有比ArrayList更好的性能.但在get与set方面弱于ArrayList- LinkedList 还实现了 Queue 接口,该接口比List提供了更多的方法,包括 offer(),peek(),poll()等```javaimport java.util.LinkedList;import java.util.List;public class Demo {public static void main(String[] args) throws Exception {List<String> list = new LinkedList<String>();list.add("AAA");list.add("AAA");list.add("BBB");list.add("CCC");list.add("DDD");list.add(null);list.add(null);list.forEach(System.out::println);}}
Vector
- Vector 和ArrayList类似,但属于强同步类。如果你的程序本身是线程安全的(thread-safe,没有在多个线程之间共享同一个集合/对象),那么使用ArrayList是更好的选择
- Vector和ArrayList在更多元素添加进来时会请求更大的空间。Vector每次请求其大小的双倍空间,而ArrayList每次对size增长50%
- 序列化存储相同内容的Vector与ArrayList,分别到一个文本文件中去。Vector需要243字节ArrayList需要135字节,是因为ArrayList只保存了非null的数组位置上的数据,而Vector会把null值也拷贝存储 ```java import java.util.List; import java.util.Vector;
public class Demo {
public static void main(String[] args) throws Exception {
List
<a name="LavZ1"></a>### SetSet特点:元素无放入顺序,元素不可重复<a name="tiGwG"></a>#### Set新支持```javaimport java.util.Set;public class Demo {public static void main(String[] args) throws Exception {// JDK9Set<String> list = Set.of("Hello","World","你好","世界");System.out.println(list);}}
HashSet
import java.util.HashSet;import java.util.Set;public class Demo {public static void main(String[] args) {Set<String> set = new HashSet<String>();set.add("Hello");set.add("Wrold");set.add("Wrold");set.add(null);set.add(null);System.out.println(set);}}
HashSet重复元素消除
import java.util.HashSet;import java.util.Set;public class Demo {public static void main(String[] args) {Set<Person> set = new HashSet<Person>();set.add(new Person("张三", 18));set.add(new Person("李四", 16));set.add(new Person("王五", 20));set.add(new Person("王五", 12));set.add(new Person("王五", 12));set.forEach(System.out::println);}}class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}public boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}public String toString() {return "Person [name=" + name + ", age=" + age + "]";}}
TreeSet
import java.util.Set;import java.util.TreeSet;public class Demo {public static void main(String[] args) {Set<String> set = new TreeSet<String>();set.add("D");set.add("B");set.add("A");set.add("C");set.add("C");System.out.println(set);}}
TreeSet存储自定义对象
import java.util.Set;import java.util.TreeSet;public class Demo {public static void main(String[] args) {Set<Person> set = new TreeSet<Person>();set.add(new Person("张三", 18));set.add(new Person("李四", 16));set.add(new Person("王五", 20));set.add(new Person("王五", 12));set.forEach(System.out::println);}}class Person implements Comparable<Person> {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public String toString() {return "Person [name=" + name + ", age=" + age + "]";}public int compareTo(Person person) {if(person.age == age) {return person.name.compareTo(name);}else {return person.age - age;}}}
集合输出
Iterator
import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class Demo {public static void main(String[] args) {Set<String> set = new HashSet<String>();set.add("AAA");set.add("BBB");set.add("CCC");set.add("DDD");Iterator<String> iterator = set.iterator();while(iterator.hasNext()) {String str = iterator.next();if(str.equals("CCC")) {iterator.remove();}else {System.out.println(str);}}System.out.println(set);}}
ListIterator
import java.util.ArrayList;import java.util.List;import java.util.ListIterator;public class Demo {public static void main(String[] args) {List<String> list = new ArrayList<String>();list.add("AAA");list.add("BBB");list.add("CCC");list.add("DDD");ListIterator<String> listIterator = list.listIterator();while(listIterator.hasNext()) {System.out.println(listIterator.next());}System.out.println();while(listIterator.hasPrevious()) {System.out.println(listIterator.previous());}}}
Enumeration
import java.util.Enumeration;import java.util.Vector;public class Demo {public static void main(String[] args) throws Exception {Vector<String> list = new Vector<String>();list.add("AAA");list.add("AAA");list.add("BBB");list.add("CCC");list.add("DDD");list.add(null);list.add(null);Enumeration<String> elements = list.elements();while(elements.hasMoreElements()) {System.out.println(elements.nextElement());}}}
foreach
import java.util.ArrayList;import java.util.List;public class Demo {public static void main(String[] args) throws Exception {List<String> list = new ArrayList<String>();list.add("AAA");list.add("AAA");list.add("BBB");list.add("CCC");list.add("DDD");list.add(null);list.add(null);for(String str : list) {System.out.println(str);}}}
Map
Map新支持
import java.util.Map;public class Demo {public static void main(String[] args) throws Exception {// JDK9Map<String,Integer> map = Map.of("a",1,"b",2,"c",3);System.out.println(map);}}
HashMap
import java.util.HashMap;import java.util.Map;public class Demo {public static void main(String[] args) throws Exception {Map<String,Integer> map = new HashMap<String, Integer>();map.put("one", 1);System.out.println(map.put("two", 2));System.out.println(map.put("one", 101));map.put(null, 0);map.put("zero", null);System.out.println(map.get("one"));System.out.println(map.get(null));System.out.println(map.get("ten"));System.out.println(map);}}
LinkedHashMap
import java.util.LinkedHashMap;import java.util.Map;public class Demo {public static void main(String[] args) throws Exception {Map<String,Integer> map = new LinkedHashMap<String, Integer>();map.put("one", 1);System.out.println(map.put("two", 2));System.out.println(map.put("one", 101));map.put(null, 0);map.put("zero", null);System.out.println(map.get("one"));System.out.println(map.get(null));System.out.println(map.get("ten"));System.out.println(map);}}
Hashtable
import java.util.Hashtable;import java.util.Map;public class Demo {public static void main(String[] args) throws Exception {Map<String,Integer> map = new Hashtable<String, Integer>();map.put("one", 1);System.out.println(map.put("two", 2));System.out.println(map.put("one", 101));System.out.println(map.get("one"));System.out.println(map.get("ten"));System.out.println(map);}}
Map输出
import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class Demo {public static void main(String[] args) throws Exception {Map<String,Integer> map = new HashMap<String, Integer>();map.put("one", 1);map.put("two", 2);Set<Entry<String, Integer>> set = map.entrySet();// 遍历方式1Iterator<Entry<String, Integer>> iterator = set.iterator();while(iterator.hasNext()) {Entry<String, Integer> entry = iterator.next();System.out.println(entry.getKey() + ":" + entry.getValue());}// 遍历方式2for(Entry<String, Integer> entry : set) {System.out.println(entry.getKey() + ":" + entry.getValue());}// 遍历方式3Set<String> keySet = map.keySet();for(String key : keySet) {System.out.println(key + ":" + map.get(key));}// 遍历值Collection<Integer> values = map.values();for(Integer value : values) {System.out.println(value);}}}
Map自定义key
import java.util.HashMap;import java.util.Map;public class Demo {public static void main(String[] args) throws Exception {Map<Person,String> map = new HashMap<Person,String>();map.put(new Person("张三", 18), "张三丰");System.out.println(map.get(new Person("张三", 18)));}}class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}public boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}public String toString() {return "Person [name=" + name + ", age=" + age + "]";}}
集合工具
Stack栈
import java.util.Stack;public class Demo {public static void main(String[] args) throws Exception {Stack<String> stack = new Stack<String>();stack.push("AAAA");stack.push("BBBB");stack.push("CCCC");stack.push("DDDD");System.out.println(stack.pop());System.out.println(stack.pop());System.out.println(stack.pop());System.out.println(stack.pop());System.out.println(stack.pop());// 报错}}
Queue队列
import java.util.LinkedList;import java.util.PriorityQueue;import java.util.Queue;public class Demo {public static void main(String[] args) throws Exception {Queue<String> queue = new LinkedList<String>();queue.offer("C");queue.offer("B");queue.offer("A");System.out.println(queue.poll());System.out.println(queue.poll());System.out.println(queue.poll());System.out.println("--------------------");Queue<String> queue2 = new PriorityQueue<String>();queue2.offer("C");queue2.offer("B");queue2.offer("A");System.out.println(queue2.poll());System.out.println(queue2.poll());System.out.println(queue2.poll());}}
Properties
import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.util.Properties;public class Demo {public static void main(String[] args) throws Exception {File file = new File("test.properties");Properties prop = new Properties();prop.setProperty("a", "AAA");prop.setProperty("b", "Hello World");prop.setProperty("c", "你好 世界");prop.store(new FileWriter(file), "Notes 注释");Properties prop2 = new Properties();prop2.load(new FileReader(file));System.out.println(prop2.get("c"));}}
Collections
Collection 是一个集合接口,它提供了对集合对象进行基本操作的通用接口方法
Collections 是一个包装类,它包含有各种有关集合操作的静态多态方法
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Demo {public static void main(String[] args) throws Exception {List<String> list = new ArrayList<String>();Collections.addAll(list, "BBB", "CCC", "AAA");System.out.println(list);Collections.reverse(list);//反转System.out.println(list);Collections.sort(list);//排序System.out.println(list);System.out.println(Collections.binarySearch(list, "CCC"));//排好序后二分查找}}
SynchronizedList和Vector的区别
- SynchronizedList有很好的扩展和兼容功能。他可以将所有的List的子类转成线程安全的类
- 使用SynchronizedList的时候,进行遍历时要手动进行同步处理
- SynchronizedList可以指定锁定的对象 ```java import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Vector;
public class Demo {
public static void main(String[] args) throws Exception {
Vector
<a name="snOsn"></a>### Stream数据流<a name="Ww4x8"></a>#### Stream基本操作```javaimport java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class Demo {public static void main(String[] args) throws Exception {List<String> list = new ArrayList<String>();Collections.addAll(list, "Java", "JavaScript", "HTML", "CSS", "jQuery");Stream<String> stream = list.stream();List<String> result = stream.filter((ele)->ele.toLowerCase().contains("j")).skip(1).limit(2).collect(Collectors.toList());System.out.println(result);}}
网络编程
C/S模型
import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Scanner;public class EchoServer {public static void main(String[] args) throws Exception {ServerSocket server = new ServerSocket(9999);System.out.println("等待客户端连接........");Socket client = server.accept();Scanner scanner = new Scanner(client.getInputStream());scanner.useDelimiter("\r\n");PrintStream stream = new PrintStream(client.getOutputStream());boolean flag = true;while(flag) {if(scanner.hasNext()) {String string = scanner.next();if("byebye".equalsIgnoreCase(string)) {stream.println("ByeBye....");flag = false;}else {stream.println("[echo]" + string);}}}scanner.close();stream.close();client.close();server.close();}}
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;import java.util.Scanner;public class EchoClient {private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));public static void main(String[] args) throws Exception {Socket client = new Socket("localhost", 9999);Scanner scanner = new Scanner(client.getInputStream());scanner.useDelimiter("\r\n");PrintStream stream = new PrintStream(client.getOutputStream());boolean flag = true;while(flag) {String input = getString("请输入要发送的内容:");stream.println(input);if(scanner.hasNext()) {System.out.println(scanner.next());}if("byebye".equalsIgnoreCase(input)) {flag = false;}}scanner.close();stream.close();client.close();}public static String getString(String prompt) throws Exception {System.out.print(prompt);return KEYBOARD_INPUT.readLine();}}
BIO模型
import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Scanner;public class EchoServer {private static class ClientThread implements Runnable {private Socket client = null;private Scanner scanner = null;private PrintStream stream = null;private boolean flag = true;public ClientThread(Socket client) throws Exception {this.client = client;this.scanner = new Scanner(client.getInputStream());this.scanner.useDelimiter("\r\n");this.stream = new PrintStream(client.getOutputStream());}public void run() {while(flag) {if(scanner.hasNext()) {String string = scanner.next();if("byebye".equalsIgnoreCase(string)) {stream.println("ByeBye....");flag = false;}else {stream.println("[echo]" + string);}}}try {scanner.close();stream.close();client.close();} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) throws Exception {ServerSocket server = new ServerSocket(9999);System.out.println("等待客户端连接........");boolean flag = true;while(flag) {Socket client = server.accept();new Thread(new ClientThread(client)).start();}server.close();}}
UDP模型
import java.net.DatagramPacket;import java.net.DatagramSocket;public class UDPClient {public static void main(String[] args) throws Exception {DatagramSocket client = new DatagramSocket(9999);byte[] data = new byte[1024];DatagramPacket packet = new DatagramPacket(data, data.length);System.out.println("客户端等待接收发送的信息.......");client.receive(packet);System.out.println("接收到的信息内容为:" + new String(data, 0, packet.getLength()));client.close();}}
import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPServer {public static void main(String[] args) throws Exception {DatagramSocket server = new DatagramSocket(9000);String str = "Hello World!!!";DatagramPacket packet = new DatagramPacket(str.getBytes(), 0, str.length(), InetAddress.getByName("localhost"), 9999);server.send(packet);System.out.println("消息发送完毕");server.close();}}
