该备忘单是针对 Java 初学者的速成课程,有助于复习 Java 语言的基本语法。
入门
Hello.java
1 2 3 4 5 6 7 8
| public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } }
|
编译和运行
1 2 3
| $ javac Hello.java $ java Hello Hello, world!
|
变量 Variables
1 2 3 4 5
| int num = 5; float floatNum = 5.99f; char letter = 'D'; boolean bool = true; String site = "jaywcjlove.github.io";
|
原始数据类型
数据类型 |
大小 |
默认 |
范围 |
byte |
1 byte |
0 |
-128 ^to^ 127 |
short |
2 byte |
0 |
-2^15^ ^to^ 2^15^-1 |
int |
4 byte |
0 |
-2^31^ ^to^ 2^31^-1 |
long |
8 byte |
0 |
-2^63^ ^to^ 2^63^-1 |
float |
4 byte |
0.0f |
N/A |
double |
8 byte |
0.0d |
N/A |
char |
2 byte |
\u0000 |
0 ^to^ 65535 |
boolean |
N/A |
false |
true / false |
字符串 Strings
1 2 3 4
| String first = "John"; String last = "Doe"; String name = first + " " + last; System.out.println(name);
|
查看: Strings
循环 Loops
1 2 3 4 5
| String word = "QuickRef"; for (char c: word.toCharArray()) { System.out.print(c + "-"); }
|
查看: Loops
数组 Arrays
1 2 3 4 5 6
| char[] chars = new char[10]; chars[0] = 'a' chars[1] = 'b' String[] letters = {"A", "B", "C"}; int[] mylist = {100, 200}; boolean[] answers = {true, false};
|
查看: Arrays
交换变量 Swap
1 2 3 4 5 6 7
| int a = 1; int b = 2; System.out.println(a + " " + b); int temp = a; a = b; b = temp; System.out.println(a + " " + b);
|
类型转换 Type Casting
1 2 3 4 5 6 7 8 9 10
|
int i = 10; long l = i;
double d = 10.02; long l = (long)d; String.valueOf(10); Integer.parseInt("10"); Double.parseDouble("10");
|
条件语句 Conditionals
1 2 3 4 5 6 7 8
| int j = 10; if (j == 10) { System.out.println("I get printed"); } else if (j > 10) { System.out.println("I don't"); } else { System.out.println("I also don't"); }
|
查看: [Conditionals](#条件语句 Conditionals)
用户输入
1 2 3 4 5
| Scanner in = new Scanner(System.in); String str = in.nextLine(); System.out.println(str); int num = in.nextInt(); System.out.println(num);
|
Java 字符串
基本的
1 2 3
| String str1 = "value"; String str2 = new String("value"); String str3 = String.valueOf(123);
|
字符串连接
1 2 3 4 5 6
| String s = 3 + "str" + 3; String s = 3 + 3 + "str"; String s = "3" + 3 + "str"; String s = "3" + "3" + "23"; String s = "" + 3 + 3 + "23"; String s = 3 + 3 + 23;
|
字符串生成器
1
| StringBuilder sb = new StringBuilder(10);
|
1 2 3 4
| ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | | | | | | | | | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9
|
1 2 3 4
| ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | R | e | f | e | r | e | n | c | e | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9
|
1 2 3 4
| ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | R | e | f | | | | | | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9
|
1 2 3 4
| ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | M | y | | R | e | f | | | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9
|
1 2 3 4
| ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | M | y | | R | e | f | ! | | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9
|
比较
1 2 3 4 5
| String s1 = new String("QuickRef"); String s2 = new String("QuickRef"); s1 == s2 s1.equals(s2) "AB".equalsIgnoreCase("ab")
|
操纵
1 2 3 4 5 6 7
| String str = "Abcd"; str.toUpperCase(); str.toLowerCase(); str.concat("#"); str.replace("b", "-"); " abc ".trim(); "ab".toCharArray();
|
信息
1 2 3 4 5 6 7 8 9 10 11 12
| String str = "abcd"; str.charAt(2); str.indexOf("a") str.indexOf("z") str.length(); str.toString(); str.substring(2); str.substring(2,3); str.contains("c"); str.endsWith("d"); str.startsWith("a"); str.isEmpty();
|
不可变
1 2 3 4
| String str = "hello"; str.concat("world");
System.out.println(str);
|
1 2 3 4
| String str = "hello"; String concat = str.concat("world");
System.out.println(concat);
|
一旦创建就不能修改,任何修改都会创建一个新的String
Java 数组
声明 Declare
1 2 3 4 5 6 7
| int[] a1; int[] a2 = {1, 2, 3}; int[] a3 = new int[]{1, 2, 3}; int[] a4 = new int[3]; a4[0] = 1; a4[2] = 2; a4[3] = 3;
|
修改 Modify
1 2 3 4 5
| int[] a = {1, 2, 3}; System.out.println(a[0]); a[0] = 9; System.out.println(a[0]); System.out.println(a.length);
|
循环 (读 & 写)
1 2 3 4 5 6
| int[] arr = {1, 2, 3}; for (int i=0; i < arr.length; i++) { arr[i] = arr[i] * 2; System.out.print(arr[i] + " "); }
|
Loop (Read)
1 2 3 4 5
| String[] arr = {"a", "b", "c"}; for (int a: arr) { System.out.print(a + " "); }
|
二维数组 Multidimensional Arrays
1 2 3 4 5 6 7 8 9 10
| int[][] matrix = { {1, 2, 3}, {4, 5} }; int x = matrix[1][0];
Arrays.deepToString(matrix) for (int i = 0; i < a.length; ++i) { for(int j = 0; j < a[i].length; ++j) { System.out.println(a[i][j]); } }
|
排序 Sort
1 2 3 4
| char[] chars = {'b', 'a', 'c'}; Arrays.sort(chars);
Arrays.toString(chars);
|
Java 条件语句
运算符
+
(加法运算符(也用于字符串连接))
-
(减法运算符)
*
(乘法运算符)
/
(分区运算符)
%
(余数运算符)
=
(简单赋值运算符)
++
(增量运算符;将值增加 1)
--
(递减运算符;将值减 1)
!
(逻辑补码运算符;反转布尔值)
==
(等于)
!=
(不等于)
>
(比…更棒)
>=
(大于或等于)
<
(少于)
<=
(小于或等于)
&&
条件与
||
条件或
- ?: 三元(if-then-else 语句的简写)
instanceof
(将对象与指定类型进行比较)
~
(一元按位补码)
<<
(签名左移)
>>
(有符号右移)
>>>
(无符号右移)
&
(按位与)
^
(按位异或)
|
(按位包含 OR)
If else
1 2 3 4 5 6 7 8
| int k = 15; if (k > 20) { System.out.println(1); } else if (k > 10) { System.out.println(2); } else { System.out.println(3); }
|
Switch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| int month = 3; String str; switch (month) { case 1: str = "January"; break; case 2: str = "February"; break; case 3: str = "March"; break; default: str = "Some other month"; break; }
System.out.println("Result " + str);
|
三元运算符
1 2 3 4 5
| int a = 10; int b = 20; int max = (a > b) ? a : b;
System.out.println(max);
|
逻辑运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| if (condition1 && condition2) { }
if (condition1 || condition2) { }
if (!condition) { }
|
比较运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| if (a == b) { }
if (a != b) { }
if (a > b) {} if (a >= b) {} if (a < b) {} if (a <= b) {}
|
Java 循环
For 循环
1 2 3 4
| for (int i = 0; i < 10; i++) { System.out.print(i); }
|
1 2 3 4
| for (int i = 0,j = 0; i < 3; i++,j--) { System.out.print(j + "|" + i + " "); }
|
增强的 For 循环
1 2 3 4 5
| int[] numbers = {1,2,3,4,5}; for (int number: numbers) { System.out.print(number); }
|
用于循环数组或列表
While 循环
1 2 3 4 5 6
| int count = 0; while (count < 5) { System.out.print(count); count++; }
|
Do While 循环
1 2 3 4 5 6
| int count = 0; do { System.out.print(count); count++; } while (count < 5);
|
继续声明
1 2 3 4 5 6 7
| for (int i = 0; i < 5; i++) { if (i == 3) { continue; } System.out.print(i); }
|
中断语句
1 2 3 4 5 6 7
| for (int i = 0; i < 5; i++) { System.out.print(i); if (i == 3) { break; } }
|
Java 多线程
创建线程
1 2 3 4 5 6 7
| public class RunnableThread implements Runnable { @Override public void run() { } }
|
实现Callable接口,T 替换成实际类型
1 2 3 4 5 6 7
| public class CallableTask implements Callable<T> { @Override public T call() throws Exception { return null; } }
|
继承Thrad类
1 2 3 4 5 6
| public class ExtendsThread extends Thread { @Override public void run() { } }
|
运行线程
1 2 3 4 5 6 7
| public static void main(String[] args) throws ExecutionException, InterruptedException { new Thread(new RunnableThread()).start(); new ExtendsThread2().start(); FutureTask<Integer> integerFutureTask = new FutureTask<>(new CallableTask()); integerFutureTask.run(); }
|
线程池
- corePoolSize: 核心线程数
- maximumPoolSize: 最大线程数
- keepAliveTime: 线程空闲时间
- timeUni: 线程空闲时间单位
- workQueue: 线程等待队列
- threadFactory: 线程创建工厂
- handler: 拒绝策略
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 2, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new DefaultThreadFactory("pollName"), new ThreadPoolExecutor.CallerRunsPolicy() );
Executors.newCachedThreadPool(); Executors.newFixedThreadPool(10); Executors.newScheduledThreadPool(10); Executors.newSingleThreadExecutor();
|
synchronized
1 2 3 4 5 6 7 8 9 10
| synchronized(obj) { ... }
public synchronized (static) void methodName() { ... }
|
线程编排
1 2 3 4 5 6 7 8 9 10
| CountDownLatch countDownLatch = new CountDownLatch(2); new Thread(() -> { try { ... }finally { countDownLatch.countDown(); } }).start(); countDownLatch.await();
|
CompletableFuture
1 2 3 4
| CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {}); CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {}); CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {}); CompletableFuture.allOf(task1, task2, task3).get();
|
Semaphore
1 2 3 4 5 6
| Semaphore semaphore = new Semaphore(5); try { semaphore.acquire(); } finally { semaphore.release(); }
|
ThreadLocal
1 2
| ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
|
使用完之后一定要记得 remove
, 否则会内存泄露
1 2 3
| threadLocal.set(1); threadLocal.get(); threadLocal.remove();
|
线程等待与唤醒
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| wait(); notify(); notifyAll();
ReentrantLock lock = new ReentrantLock(); Condition condition= lock.newCondition(); lock.lock(); try{ condition.await(); condition.signal(); condition.signalAll(); } finally { lock.unlock }
LockSupport.park(obj); LockSupport.unpark(thread);
|
Java 框架搜集
Java 集合
ArrayList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| List<Integer> nums = new ArrayList<>();
nums.add(2); nums.add(5); nums.add(8);
System.out.println(nums.get(0));
for (int i = 0; i < nums.size(); i++) { System.out.println(nums.get(i)); } nums.remove(nums.size() - 1); nums.remove(0); for (Integer value : nums) { System.out.println(value); }
nums.forEach( e -> System.out.println(e.toString()) );
|
HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13
| Map<Integer, String> m = new HashMap<>(); m.put(5, "Five"); m.put(8, "Eight"); m.put(6, "Six"); m.put(4, "Four"); m.put(2, "Two");
System.out.println(m.get(6));
m.forEach((key, value) -> { String msg = key + ": " + value; System.out.println(msg); });
|
ConcurrentHashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ConcurrentHashMap<Integer, String> m = new ConcurrentHashMap<>(); m.put(100, "Hello"); m.put(101, "Geeks"); m.put(102, "Geeks");
m.remove(101, "Geeks");
m.putIfAbsent(103, "Hello");
m.replace(101, "Hello", "For"); System.out.println(m);
|
HashSet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Set<String> set = new HashSet<>(); if (set.isEmpty()) { System.out.println("Empty!"); } set.add("dog"); set.add("cat"); set.add("mouse"); set.add("snake"); set.add("bear"); if (set.contains("cat")) { System.out.println("Contains cat"); } set.remove("cat"); for (String element : set) { System.out.println(element); } set.forEach( e -> System.out.println(e.toString()) );
|
ArrayDeque
1 2 3 4 5 6 7 8 9 10 11 12 13
| Deque<String> a = new ArrayDeque<>();
a.add("Dog");
a.addFirst("Cat");
a.addLast("Horse");
System.out.println(a);
System.out.println(a.peek());
System.out.println(a.pop());
|
Java I/O流
常见的类和操作
字节流
InputStream
字节输入流的抽象基类
FileInputStream
从文件中读取字节的输入流
ByteArrayInputStream
从字节数组中读取字节的输入流
OutputStream
字节输出流的抽象基类
FileOutputStream
向文件中写入字节的输出流
ByteArrayOutputStream
将字节写入到字节数组的输出流
字符流
Reader
字符输入流的抽象基类
FileReader
从文件中读取字符的输入流
BufferedReader
带缓冲区的字符输入流
InputStreamReader
字节流到字符流的桥接器
Writer
字符输出流的抽象基类
FileWriter
向文件中写入字符的输出流
BufferedWriter
带缓冲区的字符输出流
OutputStreamWriter
字符流到字节流的桥接器
对象流
ObjectInputStream
从输入流中读取Java对象的流
ObjectOutputStream
将Java对象写入输出流的流
缓冲流
BufferedInputStream
带缓冲区的字节输入流
BufferedOutputStream
带缓冲区的字节输出流
BufferedReader
带缓冲区的字符输入流
BufferedWriter
带缓冲区的字符输出流
数据流
DataInputStream
从输入流中读取基本数据类型的数据
DataOutputStream
将基本数据类型数据写入输出流
文件类
File
文件和目录路径名的抽象表示
FileReader
从文件中读取字符的输入流
FileWriter
向文件中写入字符的输出流
输入输出异常处理
IOException
Java I/O操作中的通用异常
FileNotFoundException
当试图打开指定文件失败时抛出
EOFException
在尝试读取流的末尾时抛出
其他流
PrintStream
打印格式化表示的对象的输出流
PrintWriter
格式化的文本输出流
RandomAccessFile
随机访问文件的类,支持读取和写入操作
字节流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| InputStream inputStream = new FileInputStream("input.txt");
OutputStream outputStream = new FileOutputStream("output.txt");
InputStream bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
|
字符流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Reader fileReader = new FileReader("input.txt");
Writer fileWriter = new FileWriter("output.txt");
Reader bufferedFileReader = new BufferedReader( new FileReader("input.txt") );
Writer bufferedFileWriter = new BufferedWriter( new FileWriter("output.txt") );
|
数据流
1 2 3 4 5 6 7
| DataInputStream dataInputStream = new DataInputStream(inputStream);
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
|
对象流
1 2 3 4 5 6 7
| ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
|
序列化与反序列化
序列化对象到文件
1 2 3 4 5 6
| try ( ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("object.dat")) ) { objectOutputStream.writeObject(object); }
|
从文件反序列化对象
1 2 3 4 5 6
| try ( ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("object.dat")) ) { Object object = objectInputStream.readObject(); }
|
标准输入输出流
标准输入流
1 2
| InputStream standardInputStream = System.in;
|
标准输出流
1 2
| PrintStream standardOutputStream = System.out;
|
基本操作
1 2 3 4 5 6 7 8 9 10 11
| int byteData = inputStream.read();
outputStream.write(byteData);
int charData = reader.read();
writer.write(charData);
|
关闭流
1 2 3 4 5
| inputStream.close();
outputStream.close();
|
Java Stream 流
创建流
从集合创建流
1 2
| List<String> list = Arrays.asList("a", "b", "c"); Stream<String> streamFromList = list.stream();
|
从数组创建流
1 2
| String[] array = {"d", "e", "f"}; Stream<String> streamFromArray = Arrays.stream(array);
|
创建空流
1
| Stream<String> emptyStream = Stream.empty();
|
创建无限流
1
| Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 2);
|
中间操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Stream<String> filteredStream = list.stream().filter( s -> s.startsWith("a") );
Stream<Integer> mappedStream = list.stream().map(String::length);
Stream<String> sortedStream = list.stream().sorted();
Stream<String> distinctStream = list.stream().distinct();
Stream<String> limitedStream = list.stream().limit(2);
Stream<String> skippedStream = list.stream().skip(1);
|
终端操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| Optional<String> anyElement = list.stream().findAny(); Optional<String> firstElement = list.stream().findFirst(); long count = list.stream().count(); Optional<String> maxElement = list.stream() .max(Comparator.naturalOrder()); Optional<String> minElement = list.stream() .min(Comparator.naturalOrder());
boolean anyMatch = list.stream().anyMatch(s -> s.contains("a")); boolean allMatch = list.stream().allMatch(s -> s.length() == 1); boolean noneMatch = list.stream().noneMatch(s -> s.contains("z"));
Optional<String> reducedString = list.stream() .reduce((s1, s2) -> s1 + s2); String reducedStringWithIdentity = list.stream() .reduce("Start:", (s1, s2) -> s1 + s2);
List<String> collectedList = list.stream() .collect(Collectors.toList()); Set<String> collectedSet = list.stream() .collect(Collectors.toSet()); Map<Integer, String> collectedMap = list.stream() .collect( Collectors.toMap(String::length, Function.identity()) );
|
并行流
1 2 3 4
| List<String> list = Arrays.asList("a", "b", "c", "d", "e"); List<String> upperCaseList = list.parallelStream() .map(String::toUpperCase) .collect(Collectors.toList());
|
反射
这些是使用 Java 反射时常见的操作。使用反射需要注意性能和安全性问题,尽量避免在性能要求高的地方过度使用。
获取 Class 对象
1 2 3 4 5 6 7 8 9
| Class<?> clazz1 = MyClass.class;
MyClass obj = new MyClass(); Class<?> clazz2 = obj.getClass();
Class<?> clazz3 = Class.forName("com.example.MyClass");
|
获取类的信息
获取类的名称
1
| String className = clazz.getName();
|
获取类的修饰符
1
| int modifiers = clazz.getModifiers();
|
获取类的包信息
1
| Package pkg = clazz.getPackage();
|
获取类的父类
1
| Class<?> superClass = clazz.getSuperclass();
|
获取类实现的接口
1
| Class<?>[] interfaces = clazz.getInterfaces();
|
创建对象实例
1 2 3 4 5 6
| MyClass instance = (MyClass) clazz.newInstance();
Constructor<?> constructor = clazz.getConstructor(String.class, int.class); MyClass instanceWithArgs = (MyClass) constructor.newInstance("example", 123);
|
获取和设置字段值
1 2 3 4 5 6 7
| Field field = clazz.getDeclaredField("fieldName"); field.setAccessible(true); Object value = field.get(instance);
field.set(instance, newValue);
|
处理泛型
1 2
| Type genericType = field.getGenericType();
|
调用方法
1 2 3 4 5 6
| Method method = clazz.getDeclaredMethod("methodName", parameterTypes); method.setAccessible(true);
Object result = method.invoke(instance, args);
|
其他常用操作
1 2 3 4 5 6 7 8 9
| boolean isArray = clazz.isArray(); boolean isEnum = clazz.isEnum(); boolean isAnnotation = clazz.isAnnotation();
Constructor<?>[] constructors = clazz.getConstructors(); Field[] fields = clazz.getDeclaredFields(); Method[] methods = clazz.getDeclaredMethods();
|
处理注解
1 2
| Annotation annotation = field.getAnnotation(MyAnnotation.class);
|
方法引用
方法引用
Java 的 Consumer
接口里的 accept
方法接受参数但不返回值。要让它打印传入的参数,可以这样做:
1 2 3 4 5 6 7
| Consumer<String> test = new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }; test.accept("test");
|
更简单的,我们可以直接传入Lambda表达式
1
| Consumer<String> test = System.out::println;
|
方法引用通过方法的名字指向一个方法,使语言构造更简洁,减少冗余代码。
使用方式
静态方法引用
1 2 3 4
| Comparator<Integer> comparator = Math::max;
int result = comparator.compare(1, 2);
|
实例方法引用
1 2 3 4
| String str = "HELLO";
String lowerCase = str::toLowerCase;
|
构造方法引用
1 2 3 4
| Supplier<String> supplier = String::new;
String str = supplier.get();
|
数组构造方法引用
1 2 3 4 5
| Function<Integer, String[]> function = String[]::new;
String[] array = function.apply(5);
|
对象中的方法引用
1 2 3 4
| String someStr = "HELLO";
String lowerCase = someStr::toLowerCase;
|
对象中的静态方法引用
1 2 3 4
| SomeClass someObject = new SomeClass();
int result = someObject::staticMethod;
|
杂项 Misc
访问修饰符
修饰符 |
Class |
Package |
Subclass |
World |
public |
Y |
Y |
Y |
Y |
protected |
Y |
Y |
Y |
N |
no modifier |
Y |
Y |
N |
N |
private |
Y |
N |
N |
N |
常用表达
1 2 3 4 5 6
| String text = "I am learning Java";
text.replaceAll("\\s+", "");
text.split("\\|"); text.split(Pattern.quote("|"));
|
查看: Regex in java
关键字
- abstract
- continue
- for
- new
- switch
- assert
- default
- goto
- package
- synchronized
- boolean
- do
- if
- private
- this
- break
- double
- implements
- protected
- throw
- byte
- else
- import
- public
- throws
- case
- enum
- instanceof
- return
- transient
- catch
- extends
- int
- short
- try
- char
- final
- interface
- static
- void
- class
- finally
- long
- strictfp
- volatile
- const
- float
- native
- super
- while
数学方法
方法 |
说明 |
Math.max(a,b) |
a 和 b 的最大值 |
Math.min(a,b) |
a 和 b 的最小值 |
Math.abs(a) |
绝对值 |
Math.sqrt(a) |
a 的平方根 |
Math.pow(a,b) |
b 的幂 |
Math.round(a) |
最接近的整数 |
Math.sin(ang) |
正弦 |
Math.cos(ang) |
ang 的余弦 |
Math.tan(ang) |
ang 的切线 |
Math.asin(ang) |
ang 的反正弦 |
Math.log(a) |
a 的自然对数 |
Math.toDegrees(rad) |
以度为单位的角度弧度 |
Math.toRadians(deg) |
以弧度为单位的角度度 |
异常 Try/Catch/Finally
1 2 3 4 5 6 7
| try { } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("always printed"); }
|
util工具类
ArrayDeque
: 可调整大小的数组双端队列,实现了Deque接口
Arrays
: 提供静态工厂,允许将数组视为列表
Collections
: 包含操作集合或返回集合的静态方法
Date
: 表示特定时间瞬间,精度为毫秒
Dictionary
: 抽象父类,可用于键值对映射,例如Hashtable
EnumMap
: 专门用于枚举键的Map实现
EnumSet
: 专门用于枚举键的Set实现
Formatter
: 提供对布局、对齐、数字、字符串和日期/时间数据的格式化支持,以及特定于语言环境的输出
SecureRandom
: 生成安全的伪随机数流的实例
UUID
: 表示不可变的通用唯一标识符
Vector
: 实现了可增长的对象数组
LocalDate
: 表示无时区的日期,仅包含年月日,不可变且线程安全,适用于Java 8及更高版本
LocalTime
: 表示无时区的时间,仅包含时分秒,不可变且线程安全,适用于Java 8及更高版本
LocalDateTime
: 表示无时区的日期时间,包含年月日时分秒,不可变且线程安全,适用于Java 8及更高版本
Collections 工具类
1 2 3 4 5 6 7 8 9 10
| List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(2); list.add(3); list.add(3); list.add(3); int frequency = Collections .frequency(list, 2);
|
另见