Java 基础

运算优先级

在Java的计算表达式中,运算优先级从高到低依次是:

  • ()
  • ! ~ ++ --
    • / %
  • << >> >>>
  • &
  • |
  • += -= *= /=

Java (三)方法与数组

二维数组与最大最小值算法

二维数组

   public static void main(String[] args){
 
     int [][] scores = {{78,98,88}, {87,96,85},{67,78,89}};
     int classLen = scores.length;
     for(int i = 0; i < classLen; i++){
       int sum = 0;
       int count =scores[i] .length;
 
       for(int j = 0; j < count; j++){
         sum += scores[i][j];
       }
       int avg = sum / count;
       System.*out*.println(((i+1)+"score is:"+avg));
     }
   }
 }
 

最大最小值

public class maxmin {
    public static void main(String[] args){

        int[] num = {12, 3, 54, 67, 88, 34};
        int max = max(num);
        int min = min(num);
        System.out.println("Max is :" + max);
        System.out.println("Min is :" + min);
    }

    public static int max(int[] num){
        int max = num[0];
        int len = num.length;
        for(int i = 1; i < len; i++){
            if(num[i] > max){
                num[i] = num[i] + max;
                max = num[i] - max;
                num[i] = num[i] - max;
            }
        }
        return max;
    }
    public static int min(int[] num){
        int min = num[0];
        int len = num.length;
        for(int i = 1; i < len; i++){
            if(num[i] < min){
                num[i] = num[i] + min;
                min = num[i] - min;
                num[i] = num[i] - min;
            }
        }
        return min;
    }
}

冒泡排序

import javax.sound.midi.SysexMessage;

public class bubblesort {
    public static void main(String[] args){

        int[] nums = {34, 4, 56, 17, 90, 65};

        for(int i=0;i< nums.length;i++){

            for(int j=0;j<nums.length-1-i;j++){

                if(nums[j] > nums[j+1]){
                    nums[j] = nums[j] + nums[j+1];
                    nums[j+1] = nums[j] - nums[j+1];
                    nums[j] = nums[j] - nums[j+1];
                }
            }
        }
        for(int n: nums){
            System.out.println(n);
        }
    }
}

选择排序

public class selectionsort {
    public static void main(String[] args){

        int[] nums = {34, 4, 56, 17, 90, 65};
        int minIndex = 0;

        for (int i=0;i<nums.length-1;i++){

            minIndex = i;
            for(int j=i+1;j<nums.length;j++){
                if(nums[minIndex]>nums[j]){
                    minIndex = j;
                }
            }
            if(minIndex!=i){
                nums[minIndex] = nums[minIndex] + nums[i];
                nums[i] = nums[minIndex] - nums[i];
                nums[minIndex] = nums[minIndex] - nums[i];
            }
        }
        for(int n:nums){
            System.out.println(n);
        }
    }
}

插入排序

public class insertionsort {
    public static void main(String[] args){

        int[] nums = {34, 4, 56, 17, 90, 65};

        for(int i=1;i<nums.length;i++){

            int temp = nums[i];
            int j = 0;
            for(j=i-1;j>=0;j--){
                if(nums[j]>temp){
                    nums[j+1] = nums[j];
                }else{
                    break;
                }
            }
            if(nums[j+1]!=temp){
                nums[j+1] = temp;
            }
        }
        for(int n:nums){
            System.out.println(n);
        }
    }
}

二分查找

public class BinarySearch {
    public static void main(String[] args){
        int[] num = {10, 20, 50, 65, 88, 90};
        int index =binarysearch(num, 88);
        System.out.println(index);
    }
    public static int binarysearch(int[] num, int key){
        int start = 0;
        int end = num.length - 1;

        while (start <= end){
            int middle = (start + end) / 2;
            if (num[middle]>key){
                end = middle - 1;
            }else if(num[middle] < key){
                start = middle + 1;
            }else{
                return middle;
            }
        }
        return -1;
    }
}

Array

利用import java.util.Arrays 二分查找

import java.util.Arrays;

public class array_binarysearch {
    public  static void main(String[] args){

        int [] num = {45, 65, 76, 87, 98, 901};

        int index = Arrays.binarySearch(num, 98);
        System.out.println(index);

        for(int n:num) {
            System.out.println(n);
        }
        System.out.println(Arrays.toString(num));

        // Quick sort
        int [] num2 = {10, 32, 11, 44, 543, 22, 12};
        Arrays.sort(num2);
        System.out.println(Arrays.toString(num2));
      
      	//Copy
      	int [] num3 = Arrays.copyOf(num2, 10);
      	System.out.println(Arrays.toString(num3));
      
				// more effiency      
      	int [] newNum = new int[num2.length];
      	System.arraycopy(num2, 0, newNum, 0, num2.length);
 		    System.out.println(Arrays.toString(newNum))
          
        // Equal or not
        System.out.println(Arrays.equals(num2, newNum));
      	
      	//fill
      	Arrays.fill(newNum, 0)
        System.out.println(Arrays.toString(newNum))
    }
}

Java (六)常用类库

String类原理分析

两种赋值方式

String name = "小白" //直接赋值

String name = new String("小白") //New

StringBuffer源码分析与常用方法

public class StringBufferDemo {
  public static void main(String[] args) {
    String a = "a";
    String b = "b";
    String c = a+b+1;
    System.out.println(c);
		
    String d = "a" +1+2+3+4+"b";
    
    StringBuffer sb = new StringBuffer();
    sb.append(a).append(b).append(1);
    System.out.println(sb.toString());
  }
}

常用操作方法

name description
public StringBuffer() 构造一个空的StringBuffer对象
public StringBuffer(String str) 将指定的String变为StringBuffer的内容
public StringBuffer(CharSequence seq) 接收CharSequence接口的实例
public StringBuffer append(datatype b) 提供了很多的append方法,用于进行字符串连接
public StringBuffer delete(int start, int end) 删除指定位置的内容
public int IndexOf(String str) 字符串查询功能
public StringBuffer insert(int offset, datatype b) 在指定位置上增加一个内容
public StringBuffer replace(int start, int end, String str) 将指定范围内容替换成其他内容
public String substring(int start, int end) 截取指定范围字符串
public StringBuffer reverse() 字符串反转

StringBuilder分析

(JDK1.5+)

public class StringBuilderDemo {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder()
  }
}

Math 与 Random

import java.util.Random;

import static java.lang.Math.floor;
public class MathDemo {
    public static void main(String[] args){

        System.out.println(Math.PI);
        System.out.println(Math.abs(-10));
        System.out.println(Math.round(Math.random()*1000)/1000.0);
        System.out.println(Math.sqrt(2));
        System.out.println(floor(1.234564));

        Random r = new Random();
        System.out.println(r.nextLong());
        System.out.println(r.nextInt());
    }
}

Date

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateDemo {
    public static void main(String[] args){
        Date date = new Date();
        //java.sql.Date sqlDate = new java.sql.Date();
        System.out.println(date);

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = new GregorianCalendar();

        int year = c1.get(Calendar.YEAR);
        int month = c1.get(Calendar.MONTH);
        int day = c1.get(Calendar.DAY_OF_MONTH);
        int hour = c1.get(Calendar.HOUR_OF_DAY);
        int minute = c1.get(Calendar.MINUTE);
        int second = c1.get(Calendar.SECOND);
        int millisecond = c1.get(Calendar.MILLISECOND);

        StringBuilder sb = new StringBuilder(50);
        sb.append(year).append("/").append(month).append("/").append(day).append(" ").append(hour).append(":").append(minute).append(":").append(second).append(" ").append(millisecond);

        System.out.println(sb.toString());

        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss SSS");
        String nowDate = df.format(new Date());
        System.out.println(nowDate);

    }
}

Comparable

自定义对象实现排序

Comparator

强制排序

Cloneable

System与Runtime

数字处理工具

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;

public class BigNum {
    public static void main(String[] args){

        String val1 = "3142353465765867876";
        String val2 = "2546576578586856745";
        BigInteger b1 = new BigInteger(val1);
        BigInteger b2 = new BigInteger(val2);

        System.out.println(b1.add(b2));
        System.out.println(b1.subtract(b2));
        System.out.println(b1.multiply(b2));
        System.out.println(b1.divide(b2));
        System.out.println(b1.remainder(b2));

        System.out.println(Arrays.toString(b1.divideAndRemainder(b2)));

        String val3 = "2312312.312312312312312";
        String val4 = "6346343.523243534534534";
        BigDecimal b3 = new BigDecimal(val3);
        BigDecimal b4 = new BigDecimal(val4);

        System.out.println(b3.add(b4));
        System.out.println(b3.subtract(b4));
        System.out.println(b3.multiply(b4));
        System.out.println(b3.scale()-b4.scale());

    }
}

MD5

Lambda

public class LambdaDemo {
    public static void main(String[] args){
        IEat ieat = new IEatImpl();
        ieat.eat();

        IEat iEat2 = new IEat(){
            @Override
            public void eat() {
                System.out.println("eat banana");
            }
        };
        iEat2.eat();

        IEat ieat3 =()->{System.out.println("eat apple");};
        ieat3.eat();
    }
}

interface IEat{
    public void eat();
}

class IEatImpl implements IEat{
    public void eat(){
        System.out.println("eat apple");
    }
}

二叉树

Java(七)文件与IO

File

public static final String separator
public File(String pathname)
public boolean createNewFile()
public boolean delete()
public boolean isDirectory()
public boolean isFile()
public String[] list()
public File[] listFiles()
public boolean mkdir()
public boolean renameTo(File dest)
public long length()
String getPath()
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class FileDemo {
    public static void main(String[] args){
        File f1 = new File("c:"+File.separator+"test"+File.separator+"vince.txt");
        if(!f1.exists()){
            try{
                f1.createNewFile();
                System.out.println("succussful");
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        System.out.println(("file or not"+ f1.isDirectory()));

        File f2 = new File("c:\\test\\my");
        boolean b = f2.delete();
        System.out.println(b);

        String[] names = f2.list();
        System.out.println(Arrays.toString(names));
      
      	for(File f:files){
          System.out.println(f.getName());
        }
        
    }
}
public class FileDemo2 {
  public static void main(String[] args){
    findFile(new File("C:\\User\\vince\\Downloads"),".jpg");
  }
  
  private static void findFile(File target, String ext){
    if(target==null) return;
    if(target.isDirectory()){
      File[] files = target.listFiles();
      if(files!=null){
        for(File f:files){
          findFile(f, ext);
        }
      }
    }else{
      String name = target.getName().toLowerCase();
      if(name.endsWith(ext)){
        System.out.println(target.getAbsolutePath());
      }
    }
  }
}

字节流

import java.io.*;

public class ByteStreamDemo {
  	private static void in(){
      File file = new File("c:\\test\\vince.txt");
      try {
        InputStream in = new FileInputStream(file);
        
        byte[] bytes = new byte[1024];
        StringBuilder buf = new StringBuilder(;)
        int len = -1;
        while((len=in.read(bytes))!=-1){
          buf.append(new String(bytes));
        }
        System.out.println(buf);
        in.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }
    private static void out(){
        File file = new File("c:\\test\\vice.txt");
        
        try{
            OutputStream out = new FileOutputStream(file);
            String info = "abcd";
            out.write(info.getBytes());
            out.close();
            System.out.println("successful");
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  public static void main(String[] args){
    out();
    in();
  }
}

字符输入输出

public class CharStreamDemo {
    
    private static void in(){
        File file = new File("c:\\test\\test.txt");
        try {
            Reader in = new FileReader(file);
            char[] cs = new char[1];
            int len = -1;
            StringBuilder buf = new StringBuilder();
            while((len=in.read(cs))!=-1){
                buf.append(new String(cs,0,len));
            }
            in.close();
            System.out.println(buf);
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static void out(){
        File file = new File("c:\\test\\test.txt");
        try {
            Writer out = new FileWriter(file, true);
            out.write(", I love you!");
            
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        out();
        in();
    }

字节流

字符流

简单文件复制

import java.io.File
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFileDemo {
    
    public static void main(String[] args) {
        copy("","")
    }
    
    private static void copy(String src, String target){
        File srcFile = new File(src);
        File targetFile = new File(target);
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(targetFile);
            
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len=in,read(bytes))!=-1){
                out.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(in!=null)in.close();
            if(out!=null)out.close();
        }
    }
}

字节字符转换流

字节缓冲流

字符缓冲流

打印流

对象流与序列化

ObjectInputStream

ObjectoutputStream

字节数组流

ByteArrayInputStream

ByteArrayOutputStream

数据流

public class DataStreamDemo {
  
  private static void read(){
    File file = new File("c:\\test\\test.dat");
    try {
      InputStream in = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(in);
      DataInputStream dis = new DataInputStream(bis);
      int num = dis.readInt();
      byte b = dis,readByte();
      String s = dis.readUTF();
      System.out.println(num+","+b+","+s);
      
      dos.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  private static void write(){
    
    File file = new File("c:\\test\\test.dat");
    try {
      OutputStream out = new FileOutputStream(file);
    	BufferedOutputstream bos = new BufferedOutputStream(out);
    	DataOutputStream dos = new DataOutputStream(bos);
    	dos.writeInt(10);
      
      dos.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  public static void main(String[] args){
    
  }
}

文件分割&文件合并

public class FileDivisionMergeDemo {
  
  private static void division(File targetFile, long cutSize) {
    if(targetFile==null)
      return;
    
    int num = targetFile.length()%cutSize==0?(int)(targetFile.length()/cutSize):(int)(targetFile.length()/cutSize+1);
    
    try {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(targetFile));
      BufferedOutputStream out = null;
      
      byte[] bytes = null;
      int len = -1;
      int count = 0;
      
      for(int i=0;i<num;i++){
        out = new BufferedOutputStream(new FileOutputStream(new File("c:\\test\\"+(i+1)+"-temp-"+targetFile.getName())));
        if(cutSize<=1024){
          bytes = new byte[(int)cutSize];
          count = 1;
        }else{
          bytes = new byte[1024];
          count = (int)cutSize/1024;
        }
        
        while(count>0 && (len=in.read(bytes))!=-1){
          out.write(bytes,0,len);
          out.flush();
          count--;
        }
        if(cutSize%1024!=0){
          bytes = new byte[(int)cutSize%1024];
          len = in.read(bytes);
          out.write(bytes,0,len);
          out.flush();
          out.close();
        }
      }
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  
  private static void merge() {
    SequenceInputStream sis = new SequenceInputStream(es);
    try {
	    BufferedOutputStream bos = new BufferedOutputStream("c:\\");
      
      byte[] bytes = new byte[1024];
      int len = -1;
      while((len=sis.read(bytes))!=-1){
        bos.write(bytes,0,len);
        bos.flush();
      }
      bos.close();
      sis.close();
      System.out.println("complete")
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

  }
  
  public static void main(String[] args) {
    File file = new File("c:\\");
    division(file,1024*1024*20);
    
    try {
      InputStream in1 = new FileInputStream(new File("c:\\"));
      InputStream in2 = new FileInputStream(new File("c:\\"));
      InputStream in3 = new FileInputStream(new File("c:\\"));
      InputStream in4 = new FileInputStream(new File("c:\\"));
      InputStream in5 = new FileInputStream(new File("c:\\"));
			
      Vector<InputStream> v = new Vector<InputStream>();
      v.add(in1);
      v.add(in2);
      v.add(in3);
      v.add(in4);
      v.add(in5);
      
      Enumeration<InputStream> es = v.elements();
			merge(es);
    } catch (FileNotFoundException e) {
      e,printStackTrace();
    } 
  }
}

字符串流与管道流

RandomAccessFile

Properties

文件压缩&文件解压

ZipOutputStream

ZipInputStream

public class CompressionAndDecompressionDemo {
  
  private static void compression(String zipFileName, File) {
    System.out.println("compressing...");
		try {
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
      BufferedOutputStream bos = new BufferedOutput(out);
      zip(out, targetFile,targetFile.getName(),bos);
      bos.close();
      out.close();
    } catch (FileNotFoundException e){
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    System.out.println("completed.")
  }
  
  private static void zip(ZipOutStream out, File targetFile, String name, BufferedOutputStream bos) throws IOException {
    if(targetFile.isDirectory()){
      File[] files = targetFile.listFiles();
      if(files.length==0){
        zOut.putNextEntry(new ZipEntry(name+"/"));
      }
      for(File f: files) {
        zip(zOut, f, name+"/"+f.getName(), bos);
      }
    }else{
      zOut.putNextEntry(new ZipEntry(name));
      FileInputStream in = new FileInputStream(targetFile);
      BufferedInputStream bis = new BufferedInputStream(in);
      
      byte[] bytes = new byte[1024];
      int len = -1;
      while((len=bis.read(bytes))!=-1){
        bos.write(bytes,0,len);
      }
      bis.close();
    }
  }
  private static void decompression(String targetFileName, String parent){
    try {
      ZipInputStream zIn = new ZipInputstream(new FileInputStream(targetFileName));
      ZipEntry entry = null;
      File file = null;
      while((entry = zIn.getNextEntry())!=null && !entry.isDirectory()){
        file = new File(parent,entry.getName());
        if(!file.exists()){
          new File(file.getParent()).mkdirs();
        }
        FileOutputStream out = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(out);
        byte[] bytes = new byte[1024];
        int len = -1;
        while((len=zIn.read(bytes))!=-1) {
          bos.write(bytes, 0, len);
        }
        bos.close();
        System.out.println(file.getAbsolutePath()+"Successful");
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    compression("c:\\text.zip", new File("c:\\text"));
    decompression("c:\\text.zip". "c:\\")
  }
}

![image-20191117144540280](/Users/mark/Library/Mobile Documents/com~apple~CloudDocs/Documents/GitHub/heyueyuan.github.io/pics/image-20191117144540280.png)

装饰者设计模式

Drink.java

public interface Drink {
  float cost();
  String description();
}

SoyaBeanMilk.java

public class SoyaBeanMilk implements Drink {
  
  @Override
  public float cost() {
    return 10f;
  }
  
  @Override
  public String description() {
    return "Pure Bean Milk";
  }
}

Decorator.java

public class Decorator implements Drink {
  
  private Drink drink;
  public Decorator(Drink drink){
    this.drink = drink;
  }
  
  @Override
  public float cost() {
    return 0;
  }
  
  @Override
  public String description() {
    return drink.description();
  }
}

SugarDecorator.java(superclass: Decorator)

public class SugarDecorator extends Decorator {
  
  public SugarDecorator(Drink drink) {
    super(drink);
  }
  
  @Override
  public float cost() {
    return super.cost()+1.0f;
  }
  
  @Override
  public String description() {
    return super.description()+"+Sugar";
  }
}

BlackBeanDecorator.java

public class BlackBeanDecorator extends Decorator {
  
  public BlackBeanDecorator(Drink drink) {
    super(drink);
  }
  
  @Override
  public float cost() {
    return super.cost()+1.0f;
  }
  
  @Override
  public String description() {
    return super.description()+"+Black Bean";
  }
}

EggDecorator.java

public class EggDecorator extends Decorator {
  
  public EggDecorator(Drink drink) {
    super(drink);
  }
  
  @Override
  public float cost() {
    return super.cost()+1.0f;
  }
  
  @Override
  public String description() {
    return super.description()+"+Egg";
  }
}

Test.java

public class Text {
  
  public static void main(String[] args){
    Drink drink = new SoyaBeanMilk();
    SugarDecorator sugar = new SugarDecorator(drink);
    EggDecorator egg = new EggDecorator(sugar);
    BlackBeanDecorator blackBean = new BlackBeanDecorator(egg);
    
    System.out.println(blackBean.description());
		System.out.println(blackBean.cost());
  }
}

常见字符模式

NIO基本概念与缓冲区

通道文件操作与内存映射

Path接口与Files工具类

Java教程(八)集合

Java教程(九)多线程与并发

Java教程(十)网络编程

Java教程(十一)反射与内省

Java教程(十二)泛型、正则表达式、枚举、注解、XML和JSON、GUI事件处理

视频教程