API

API:Application Programming Interface应用编程接口,一切可以调用的东西都是API

Scanner 类

  • Scanner sc = new Scanner(System.in);        连接键盘
  • sc.hasNextInt()                              判断下一个是否为整数
  • int num = sc.nextInt();                     接收整数
  • String s = sc.nextLine();                     结束标记是:换行符
  • String s2 = sc.next();                      结束标记是:空白字符(空格,tab,换行符)
  • sc.close();                                 关闭流

Scanner scanner = new Scanner(System.in);//等待输入 String s = scanner.next();//空格以后的没有 System.out.println(s); scanner.hasNextLine();//判断是否还在输入 String s = scanner.nextLine();//全部拿到 System.out.println(s); scanner.close();//关闭IO流 //scanner.nextInt();整数

Object(只有一个无参构造)

object是所有类的父类/根类

所有的类都可以使用object的所有内容

==比较基本类型的数据,比的值本身;比较引用类型的数据,比的是地址值

Object o = new Object();
System.out.println(o.toString());//java.lang.Object@1b6d3586 获取o对象在内存中的地址值
System.out.println(o.hashCode());//460141958   获取o对象的哈希码值
System.out.println(o.equals("abc"));//false     比较o对象和"abc"对象是否相等

String + 一点点数组

char[] arr = {'h','e','l','l','o'}; String s = new String(arr); int[] i = {1,2,3,4,5}; System.out.println(s);//hello System.out.println(s.charAt(0));//h 获取0下标的数据 System.out.println(s.concat("xyz"));//helloxyz 在后面拼接字符串 System.out.println(s.contains("ell"));//true 判断是否包含"ell" System.out.println(s.endsWith("ll"));//false 判断是否以"ll"结尾 System.out.println(s.startsWith("hell"));//true 判断是否以"hell"开始 System.out.println(s.equals("hello"));//true 判断是否与hello"相等 byte[] bs = s.getBytes();//查询ascii码表把每个字符变成整数存入byte[] System.out.println(bs);//[B@1b6d3586 System.out.println(Arrays.toString(bs));//[104, 101, 108, 108, 111] 打印数组元素 System.out.println(s.hashCode());//99162322 获取s的哈希码值 System.out.println(s.isEmpty());//false 判断s是否为空 System.out.println(s.indexOf("l"));//2 获取l在s字符串里第一次出现的索引 System.out.println(s.lastIndexOf("l"));//3 获取l在s字符串里最后一次出现的索引 System.out.println(s.length());//5 获取s的长度 System.out.println(s.replace("l","6"));//he66o 把s里的所有l,换成6 String[] ss = s.split("e");//把字符串按照规则切割 System.out.println(Arrays.toString(ss));//[h, llo] System.out.println(s.substring(2));//llo 截取子串,从2到结束 System.out.println(s.substring(2,4));//ll 截取子串,从2开始到4结束,含头不含尾[2,4) System.out.println(s.toUpperCase());//HELLO 全转大写 System.out.println(s.toLowerCase());//hello 全转小写 char[] cs = s.toCharArray();//把字符串里的数据存入char[] System.out.println(cs[0]);//h String s2 = " 1 2 34 "; System.out.println(s2.trim());//1 2 34 去除多余空格(前后) System.out.println(); String s3 = String.valueOf(100);//把其他类型 转成字符串类型 System.out.println(s3);//100 System.out.println(s3+1);//1001 int[] i1 = {23,12,42,1,2,55,6,23}; Arrays.sort(i1);//对数组进行排序 System.out.println(Arrays.toString(i1)); int[] i3 = Arrays.copyOf(i1,4);//第一个参数:原数组名;第二个参数:新数组长度 System.out.println(Arrays.toString(i3));//[1, 2, 6, 12]

char[] c = s.toCharAray //将字符串转换成字符数组(a=97)

计时

Long start = System.currentTimeMillis();//获取当前时间(毫秒)     1s = 1000ms

StringBuilder/StringBuffer(专门用来优化字符串拼接效率)

1、封装了char[]数组

2、 是可变的字符序列

3、 提供了一组可以对字符内容修改的方法

4、 常用append()来代替字符串做字符串连接

5、 内部字符数组默认初始容量是16:initial capacity of 16 characters

6、 如果大于16会尝试将扩容,新数组大小原来的变成2倍+2,容量如果还不够,直接扩充到需要的容量大小。int newCapacity = value.length * 2 + 2;

7、 StringBuffer 1.0出道线程安全,StringBuilder1.5出道线程不安全

StringBuilder比StringBuffer快

StringBuilder(这是扩展的)

StringBuilder sb = new StringBuilder(); 无参构造

StringBuilder sb2 = new StringBuilder("abc") 将String类型的“abc”转成StringBuilder类型的对象

sb2.append("随意") 追加字符串

String s = sb2.toString(); 将StringBuilder类型的“abc随意”转成String类型的对象

包装类

专门用来给对应的基本类型提供丰富的方法

数字包装类的抽象父类—— Number 专门抽取了数字包装类的共性方法

用来把 包装类 转成 基本类型 的各种方法

  • byte——Byte

  • short——Short

  • int——Integer

  • long——Long

  • float——Float

  • double——Double

  • boolean——Boolean

  • char——Character

Integer i = new Integer(5);
System.out.println(i+5);//10   运算时可以自动拆箱
System.out.println(Integer.valueOf(5));//5   把基本类型的5转换为包装类型
System.out.println(i.intValue());//5   把包装类型转换为基本类型
System.out.println(Integer.parseInt("123")+1);//124   把字符串的整数转换为int类型
System.out.println(Integer.toBinaryString(5));//101 把5转换为2进制
System.out.println(Integer.toOctalString(33));//41   把33转换为8进制
System.out.println(Integer.toHexString(15));//f     把15转换为16进制

Date和Calendar类 日期和日历类

日期类Date 和 SimpleDateFormat配合

时间戳 自1970年1月1日00:00:00起

专门用来解析日期的数据

Date date = new Date();
System.out.println(date.getDate());//10             今天是那一日
System.out.println(date.getDay());//3               今天是周几
System.out.println(date.getHours());//14             现在是几点
System.out.println(date.getMinutes());//40           现在是哪一分钟
System.out.println(date.getMonth());//2              今天是几月
System.out.println(date.getSeconds());//50           现在是多少秒
System.out.println(date.getTime());//1615358450297   自1970年1月1日00:00:00起到现在的毫秒值
System.out.println(date.getYear());//121              从1900年到现在多少年
System.out.println(date.toLocaleString());//2021-3-10 14:40:50

日期工具SimpleDateFormat 和Date相互配合

专门用来格式化日期数据 平时存储日期是用字符串的格式,需要相互转换

把两种类型的日期数据互转,String<——>Date

String s = "1994-12-01 ";
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");//y表示年,M表示月,d表示日
Date d = sd.parse(s);//把字符串日期转换为Date格式
long start = d.getTime();
long now = System.currentTimeMillis();
System.out.println((now-start)/1000/60/60/24/365);//26

BigDecimal/BigInteger

BigDecimal:常用来解决精确的浮点数运算。

BigDecimal.ROUND_HALF_UP 四舍五入

double d = 2.2;
double d2 = 1.2;
BigDecimal bd = new BigDecimal(d);
BigDecimal bd2 = new BigDecimal(d2);
BigDecimal bd3 = bd.subtract(bd2);
//不要用Double类型的数据,有坑,推荐使用字符串类型的数据
System.out.println(bd3);//1.0000000000000002220446049250313080847263336181640625
BigDecimal bd4 = new BigDecimal(String.valueOf(d));
BigDecimal bd5 = new BigDecimal(String.valueOf(d2));
BigDecimal bd6 = bd4.subtract(bd5);//减法
BigDecimal bd7 = bd4.add(bd5);//加法
BigDecimal bd8 = bd4.multiply(bd5);//乘法
BigDecimal bd9 = bd4.divide(bd5);//除法 除法报错,小数运算除不尽ArithmeticException
BigDecimal bd9 = bd4.divide(bd5,4,BigDecimal.ROUND_HALF_UP);
//第一个参数是参与运算的数,第二个参数是保留的小数位,第三个参数是四舍五入
System.out.println(bd6 + " " + bd7 + " " + bd8 + " " + bd9 );//1.0

BigInteger:常用来解决超大的整数运算。

IO流

File文件流

File file = new File("D:\\iotest\\2.txt");//参数是指定文件路径
System.out.println(file.length());//3                       文件的字节量
System.out.println(file.exists());//true                    判断是否存在
System.out.println(file.isFile());//true                     判断是否为文件
System.out.println(file.isDirectory());//false               判断是否为文件夹
System.out.println(file.getName());//1.txt                  获取名称
System.out.println(file.getParent());//D:\iotest              获取父路径
System.out.println(file.getAbsolutePath());//D:\iotest\1.txt   获取完整的路径
System.out.println(file.createNewFile());//true     创建不存在的文件,如果文件已经存在,会失败;如果文件夹不存在会异常
file = new File("D:\\iotest\\a");
System.out.println(file.mkdir());//true                创建不存在的文件夹
file = new File("D:\\iotest\\x\\y\\z");
System.out.println(file.mkdirs());//true            创建多层不存在的文件夹
System.out.println(file.delete());//                删除空的文件夹或者文件
//TODO 列表方法(列出文件夹里的所有资源)
file = new File("D:\\iotest");
String[] s = file.list();
System.out.println(Arrays.toString(s));//[1.txt, 2.txt, a, x]
File[] files = file.listFiles();
//列出所有资源,并且把每个资源封装成File对象,存入File[]
System.out.println(Arrays.toString(files));
//[D:\iotest\1.txt, D:\iotest\2.txt, D:\iotest\a, D:\iotest\x]

字节读取流

FileInputStream子类

InputStream in = new FileInputStream("D:\\iotest\\1.txt");//参数是文件所在的路径
        //File file = new File("D:\\iotest\\2.txt");
        //InputStream in2 = new FileInputStream(file);
        InputStream in2 = new FileInputStream(new File("D:\\iotest\\2.txt"));
//        int data = in2.read();//read()一个一个的读,没数据时永远返回-1
//        System.out.println(data);//97
//        int data2 = in2.read();
//        System.out.println(data2);//98
//        int data3 = in2.read();
//        System.out.println(data3);//99
//        int data4 = in2.read();
//        System.out.println(data4);//-1
        int a = 0;
        while ((a=in.read())!=-1){
            System.out.println(a);
        }
        in.close();
        in2.close();

BufferedInputStream子类

BufferedInputStream in = new BufferedInputStream(new FileInputStream("D:\\iotest\\1.txt"));
int a = 0;
while ((a=in.read())!=-1){
    System.out.println(a);
}
in.close();

FileOutputStream子类

OutputStream out = new FileOutputStream("D:\\iotest\\1.txt");
out.write(100);//d   会覆盖原文档的数据
out.close();

BufferedOutputStream子类

OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\iotest\\1.txt"));
out.write(99);
out.write("刘洋甫".getBytes(StandardCharsets.UTF_8));//写出字符串
out.close();

集合

Collection 接口

Collection<Integer> c = new ArrayList();
c.clear();//清空集合
c.add(4);//自动装箱   添加元素
c.add(3);
c.add(2);
c.add(2);
System.out.println(c.contains(2));//true   是否包含
System.out.println(c.equals(4));//false     是否相等
System.out.println(c.hashCode());//1087   哈希码值
System.out.println(c.isEmpty());//false   是否为空
System.out.println(c.remove(2));//true   移除元素(只移除一个)
System.out.println(c.size());//5           获取集合的元素个数(长度)
System.out.println(c);//[4, 3, 2]
Object[] o = c.toArray();//把c变成数组
System.out.println(Arrays.toString(o));//[4, 3, 2]
Collection<Integer> c2 = new ArrayList();
c2.add(3);
c2.add(100);
c2.add(200);
System.out.println(c.addAll(c2));//true 把c2添加到c里
System.out.println(c);//[4, 3, 2, 3, 100, 200]
System.out.println(c.containsAll(c2));//true   判断是否包含c2集合
//System.out.println(c.removeAll(c2));//true   移除c和c2的交集
//System.out.println(c);//[4, 2]
System.out.println(c.retainAll(c2));//true     保留c和c2的交集
System.out.println(c);//[3, 3, 100, 200]

//方式一
Iterator<Integer> iterator = c.iterator();//返回可以迭代集合元素的迭代器
while (iterator.hasNext()){//hasNext() 判断有元素吗?有就返回true   有元素就获取,没有就结束
  System.out.print(iterator.next()+" ");//3 3 100 200   next() 获取元素
}
System.out.println();
//方式二 foreach
for (Integer i : c){
  System.out.print(i+ " ");//3 3 100 200
}

List接口

List<String> list = new ArrayList<>();
list.add("杨幂");
list.add("古丽扎娜");
list.add("迪丽热巴");
list.add("古丽扎娜");
list.add("迪丽热巴");
list.add("Anglababa");
list.add("皮皮虾");
list.add(null);
list.add(null);
list.add(1,"hanmeimei");//在指定的索引处,添加元素
System.out.println(list.get(3));//迪丽热巴   获取指定索引的元素
System.out.println(list.indexOf("迪丽热巴"));//3  获取指定元素第一次出现的索引
System.out.println(list.lastIndexOf("迪丽热巴"));//5   获取指定元素最后一次出现的索引
System.out.println(list.remove(7));//皮皮虾   移除元素;返回被移除的元素
System.out.println(list.set(2,"888"));//古丽扎娜    替换元素;返回被替换的元素
List<String > list1 = list.subList(2, 5);//截取集合。包含2不包含5
System.out.println(list1);//[888, 迪丽热巴, 古丽扎娜]

//List集合的迭代方式
for(String s : list){
    System.out.print(s+" ");//杨幂 hanmeimei 888 迪丽热巴 古丽扎娜 迪丽热巴 Anglababa null null
}

System.out.println();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
    System.out.print(iterator.next()+" ");//杨幂 hanmeimei 888 迪丽热巴 古丽扎娜 迪丽热巴 Anglababa null null
}

System.out.println();
ListIterator<String> listIterator = list1.listIterator();
while (listIterator.hasNext()){
    System.out.print(listIterator.next()+" ");//888 迪丽热巴 古丽扎娜(顺序迭代)
}
System.out.println();
while (listIterator.hasPrevious()){//hasPrevious()判断前面有元素   previous()获取前面的元素
    System.out.print(listIterator.previous()+" ");//古丽扎娜 迪丽热巴 888(逆向迭代)
}

System.out.println();
for (int i = 0; i < list1.size(); i++) {
    System.out.print(list1.get(i)+" ");//888 迪丽热巴 古丽扎娜
}
List<Integer> list = new ArrayList<>();
list.add(100);//会自动装箱,  new Integer(100)
list.add(200);
list.add(300);
System.out.println(list.remove(0));//100
System.out.println(list.remove(new Integer(200)));//true

LinkedList

LinkedList<Integer> list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
//扩展的方法,针对首尾元素处理   2套API
list.addFirst(100);//首元素前加数据
list.addLast(200);//尾元素后加数据
System.out.println(list);//[100, 1, 2, 3, 4, 200]
System.out.println(list.getFirst());//100       获取首元素
System.out.println(list.getLast());//200         获取尾元素
System.out.println(list.removeFirst());//100     移除首元素(返回移除的元素)
System.out.println(list.removeLast());//200     移除尾元素
//另一套API
list.offerFirst(300);//首元素前加数据
list.offerLast(400);//尾元素后加数据
System.out.println(list);//[300, 1, 2, 3, 4, 400]
System.out.println(list.peekFirst());//300       获取首元素
System.out.println(list.peekLast());//400         获取尾元素
System.out.println(list.pollFirst());//300     移除首元素(返回移除的元素)
System.out.println(list.pollLast());//400     移除尾元素

迭代方式和前面的一样

HashSet

HashSet<Integer> set = new HashSet();
set.add(342);
set.add(2);
set.add(2);
set.add(32);
set.add(32);
set.add(31);
set.add(31);
set.add(23);
set.add(14);
set.add(7);

//迭代
for (Integer i : set) {
  System.out.print(i+" ");//32 2 342 23 7 14 31
}
System.out.println();
Iterator<Integer> iterator = set.iterator();
System.out.println();
while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");//32 2 342 23 7 14 31
}

Map

Map<Integer,String> map = new HashMap<>();
map.put(9527, "唐伯虎");
map.put(9528, "石榴姐");
map.put(9529, "如花");
map.put(9529, "祝枝山");
map.put(null, null);
System.out.println(map.containsKey(9527));//true        包含这个K键吗?
System.out.println(map.containsValue("123"));//false    包含这个V值吗?
System.out.println(map.equals(123));//false             判断是否相等
System.out.println(map.get(9527));//唐伯虎               根据K获取V;并返回V
System.out.println(map.hashCode());//82636759           获取哈希码值
System.out.println(map.isEmpty());//false               判断是否为空
System.out.println(map.remove(null));//null         根据K移除记录,并把V返回
System.out.println(map.size());//3                      获取map的个数(长度)

//迭代map集合
//方式一
Set<Integer> set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
    System.out.print(map.get(iterator.next())+" ");//唐伯虎 石榴姐 祝枝山
}
System.out.println();
for (Integer key : set){
    System.out.print(map.get(key)+" ");//唐伯虎 石榴姐 祝枝山
}
System.out.println();

//方式二(只能获取V值,不能获取K键)
Collection<String > collection = map.values();
for (String value : collection){
    System.out.print(value+" ");//唐伯虎 石榴姐 祝枝山
}
System.out.println();
Iterator iterator2 = collection.iterator();
while (iterator2.hasNext()){
    System.out.print(iterator2.next()+" ");//唐伯虎 石榴姐 祝枝山
}
System.out.println();

//方式三
Set<Map.Entry<Integer, String>> set1 = map.entrySet();
Iterator iterator3 = set1.iterator();//这种迭代方法好像没有getKey()和getValue()方法
while (iterator3.hasNext()){
    System.out.print(iterator3.next()+" ");//9527=唐伯虎 9528=石榴姐 9529=祝枝山
}
System.out.println();
for (Map.Entry<Integer,String> entry : set1){
    System.out.print(entry.getKey()+" ");//9527     9528   9529
    System.out.print(entry.getValue()+" ");//唐伯虎    石榴姐     祝枝山
    System.out.println();
}

Collections

List<Integer> list = new ArrayList();
Collections.addAll(list, 8,4,0,3,7,6,1,2,3,4);//第一个参数是需要给哪个集合添加数据;第二个参数是可变参数
System.out.println(Collections.max(list));//获取集合里的最大值
System.out.println(Collections.min(list));//获取集合里的最小值
System.out.println(list);//[8, 4, 0, 3, 7, 6, 1, 2, 3, 4]
Collections.reverse(list);//反转集合里的元素(只能List集合)
System.out.println(list);//[4, 3, 2, 1, 6, 7, 3, 0, 4, 8]

线程Thread

Thread thread = new Thread();
System.out.println(thread.getId());//20    获取该线程的标识符(返回值是Long类型)
thread.setName("线程一");//更改线程的名字
System.out.println(thread.getName());//线程一   获取该线程的名称
thread.run();//运行
thread.start();//开始启动
Thread.sleep(10);//让线程休眠        参数是毫秒
System.out.println(Thread.currentThread().getName());//main     获取当前正在执行线程

模拟多线程 继承extends Thread(重写run())

MyThread thread = new MyThread();
      MyThread thread2 = new MyThread();
      //thread.run();//打印10次线程名称
      //thread2.run();//run方法相对普通方法调用,没有多线程效果
      thread.start();//启动线程+执行线程的run()
      thread2.start();
  }
}
class MyThread extends Thread{
  @Override
  public void run() {
      for (int i = 0; i < 10; i++) {
          System.out.println(super.getName()+" "+i);
      }        
  }

模拟多线程 实现Runnable接口(实现run())

MyRunnable target = new MyRunnable();
      Thread thread = new Thread(target);
      Thread thread2 = new Thread(target);
      thread.start();
      thread2.start();
  }
}
class MyRunnable implements Runnable{
  @Override
  public void run() {
      for (int i = 0; i < 10; i++) {
          System.out.println(Thread.currentThread().getName()+" "+i);
      }        
  }

synchronized锁

 MyTickets tickets = new MyTickets();
      Thread thread = new Thread(tickets);
      Thread thread1 = new Thread(tickets);
      Thread thread2 = new Thread(tickets);
      Thread thread3 = new Thread(tickets);
      thread.start();
      thread1.start();
      thread2.start();
      thread3.start();
  }
}
class MyTickets implements Runnable {
  int tickets = 100;
  Object object = new Object();
  @Override
  public void run() {//public synchronized void run()
      while (true){
          synchronized(object/"123"/this){//对象锁是同一个对象就可以  
              if (tickets > 0) {
                  try {
                      Thread.sleep(10);
                  } catch (InterruptedException e) {
                      e.printStackTrace();//没啥用,会报出哪里错了
                  }
                  System.out.println(Thread.currentThread().getName() + " " + tickets--);
              } else {
                  break;
              }
          }
      }

单例模式 Singleton (饿汉式)

MySingleton m = MySingleton.getMySingleton();
      MySingleton m1 = MySingleton.getMySingleton();
      System.out.println(m==m1);//true
  }
}
class MySingleton{
  private MySingleton(){ }//不让外界随便new————私有化构造方法
  private static MySingleton mySingleton = new MySingleton();//在内部创建一个对象,给外界提供。然后封装这个成员变量
  // 这里加static   是因为要被静态资源getMySingleton()调用,必须也要是静态的
  public static MySingleton getMySingleton(){//给外界提供公共的方法,返回mySingleton     加static的原因:外界无法通过new来访问,只能通过类名直接调用
      return mySingleton;
  }

单例模式 Singleton (懒汉式)

MySingleton m = MySingleton.getMySingleton();
      MySingleton m1 = MySingleton.getMySingleton();
      System.out.println(m==m1);//true
  }
}
class MySingleton{
  private MySingleton(){ }
  private static MySingleton mySingleton;
  public static synchronized MySingleton getMySingleton(){//加锁保证数据安全(方法上或者需要加锁的地方都可以(因为是静态资源锁对象不许是 类名.class))
      if (mySingleton == null){//判断,没new过才new
          mySingleton = new MySingleton();
      }
      return mySingleton;
  }
posted @ 2021-03-12 16:21  随风L  阅读(32)  评论(0)    收藏  举报