Skip to content

Latest commit

History

History
823 lines (681 loc) · 18.5 KB

File metadata and controls

823 lines (681 loc) · 18.5 KB

Java 备忘清单

该备忘单是针对 Java 初学者的速成课程,有助于复习 Java 语言的基本语法。

入门

Hello.java

publicclassHello {
// 主要方法publicstaticvoidmain(String[] args)
{
// 输出: Hello, world!System.out.println("Hello, world!");
}
}

编译和运行

$ javac Hello.java
$ java Hello
Hello, world!

变量 Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

原始数据类型

数据类型大小默认范围
byte1 byte0-128 ^to^ 127
short2 byte0-2^15^ ^to^ 2^15^-1
int4 byte0-2^31^ ^to^ 2^31^-1
long8 byte0-2^63^ ^to^ 2^63^-1
float4 byte0.0fN/A
double8 byte0.0dN/A
char2 byte\u00000 ^to^ 65535
booleanN/Afalsetrue / false

字符串 Strings

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

查看: Strings

循环 Loops

Stringword = "QuickRef";
for (charc: word.toCharArray()) {
System.out.print(c + "-");
}
// 输出: Q-u-i-c-k-R-e-f-

查看: Loops

数组 Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

查看: Arrays

Swap

inta = 1;
intb = 2;
System.out.println(a + " " + b); // 1 2inttemp = a;
a = b;
b = temp;
System.out.println(a + " " + b); // 2 1

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

条件语句 Conditionals

intj = 10;
if (j == 10) {
System.out.println("I get printed");
} elseif (j > 10) {
System.out.println("I don't");
} else {
System.out.println("I also don't");
}

查看: [Conditionals](#条件语句 Conditionals)

用户输入

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java 字符串

基本的

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

字符串连接

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

字符串生成器

StringBuildersb = newStringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("Reference");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| R | e | f | e | r | e | n | c | e |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(3, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| R | e | f | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | R | e | f | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | R | e | f | ! | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

比较

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

操纵

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

信息

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

不可变

Stringstr = "hello";
str.concat("world");
// 输出: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// 输出: helloworldSystem.out.println(concat);

一旦创建就不能修改,任何修改都会创建一个新的String

Java 数组

声明 Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

修改 Modify

int[] a = {1, 2, 3};
System.out.println(a[0]); // 1a[0] = 9;
System.out.println(a[0]); // 9System.out.println(a.length); // 3

循环 (读 & 写)

int[] arr = {1, 2, 3};
for (inti=0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
System.out.print(arr[i] + " ");
}
// 输出: 2 4 6

Loop (Read)

String[] arr = {"a", "b", "c"};
for (inta: arr) {
System.out.print(a + " ");
}
// 输出: a b c 

Multidimensional Arrays

int[][] matrix = { {1, 2, 3}, {4, 5} };
intx = matrix[1][0]; // 4// [[1, 2, 3], [4, 5]]Arrays.deepToString(matrix)
for (inti = 0; i < a.length; ++i) {
for(intj = 0; j < a[i].length; ++j) {
System.out.println(a[i][j]);
}
}
// 输出: 1 2 3 4 5 6 7 

Sort

char[] chars = {'b', 'a', 'c'};
Arrays.sort(chars);
// [a, b, c]Arrays.toString(chars);

Java 条件语句

运算符

  • +(加法运算符(也用于字符串连接))
  • -(减法运算符)
  • *(乘法运算符)
  • /(分区运算符)
  • %(余数运算符)
  • =(简单赋值运算符)
  • ++(增量运算符;将值增加 1)
  • --(递减运算符;将值减 1)
  • !(逻辑补码运算符;反转布尔值)

  • ==(等于)
  • !=(不等于)
  • >(比...更棒)
  • >=(大于或等于)
  • <(少于)
  • <=(小于或等于)

  • &&条件与
  • ||条件或
  • ?:三元(if-then-else 语句的简写)

  • instanceof(将对象与指定类型进行比较)

  • ~(一元按位补码)
  • <<(签名左移)
  • >>(有符号右移)
  • >>>(无符号右移)
  • &(按位与)
  • ^(按位异或)
  • |(按位包含 OR)

If else

intk = 15;
if (k > 20) {
System.out.println(1);
} elseif (k > 10) {
System.out.println(2);
} else {
System.out.println(3);
}

Switch

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// 输出: Result MarchSystem.out.println("Result " + str);

三元运算符

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// 输出: 20System.out.println(max);

Java 循环

For 循环

for (inti = 0; i < 10; i++) {
System.out.print(i);
}
// 输出: 0123456789

for (inti = 0,j = 0; i < 3; i++,j--) {
System.out.print(j + "|" + i + " ");
}
// 输出: 0|0 -1|1 -2|2

增强的 For 循环

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// 输出: 12345

用于循环数组或列表

While 循环

intcount = 0;
while (count < 5) {
System.out.print(count);
count++;
}
// 输出: 01234

Do While 循环

intcount = 0;
do {
System.out.print(count);
count++;
} while (count < 5);
// 输出: 01234

继续声明

for (inti = 0; i < 5; i++) {
if (i == 3) {
continue;
}
System.out.print(i);
}
// 输出: 01245

中断语句

for (inti = 0; i < 5; i++) {
System.out.print(i);
if (i == 3) {
break;
}
}
// 输出: 0123

Java 框架搜集

Java 搜集

搜集Interface有序已排序线程安全复制Nullable
ArrayListListYNNYY
VectorListYNYYY
LinkedListList, DequeYNNYY
CopyOnWriteArrayListListYNYYY
HashSetSetNNNNOne null
LinkedHashSetSetYNNNOne null
TreeSetSetYYNNN
CopyOnWriteArraySetSetYNYNOne null
ConcurrentSkipListSetSetYYYNN
HashMapMapNNNN (key)One null(key)
HashTableMapNNYN (key)N (key)
LinkedHashMapMapYNNN (key)One null(key)
TreeMapMapYYNN (key)N (key)
ConcurrentHashMapMapNNYN (key)N
ConcurrentSkipListMapMapYYYN (key)N
ArrayDequeDequeYNNYN
PriorityQueueQueueYNNYN
ConcurrentLinkedQueueQueueYNYYN
ConcurrentLinkedDequeDequeYNYYN
ArrayBlockingQueueQueueYNYYN
LinkedBlockingDequeDequeYNYYN
PriorityBlockingQueueQueueYNYYN

ArrayList

List<Integer> nums = newArrayList<>();
// 添加nums.add(2);
nums.add(5);
nums.add(8);
// 检索System.out.println(nums.get(0));
// 为循环迭代编制索引for (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // 非常慢for (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
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));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// 使用 add()a.add("Dog");
// 使用 addFirst()a.addFirst("Cat");
// 使用 addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// 访问元素System.out.println(a.peek());
// 移除元素System.out.println(a.pop());

杂项 Misc

访问修饰符

修饰符ClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN

常用表达

Stringtext = "I am learning Java";
// 删除所有空格text.replaceAll("\\s+", "");
// 拆分字符串text.split("\\|");
text.split(Pattern.quote("|"));

查看: Regex in java

注释 Comment

// 我是单行注释!/*而我是一个多行注释!*//** * 这个 * 是 * 文档 * 注释 */

关键字

  • 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)ab 的最大值
Math.min(a,b)ab 的最小值
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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}

反射

/*** 利用反射动态加载依赖库* java9及以上版本可用* @param jar jar文件*/Methodmethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
MethodHandleaddURL = lookup.unreflect(method);
URLurl = jar.toURI().toURL();
URLClassLoaderurlClassLoader = newURLClassLoader(newURL[] {url});
addURL.invoke(urlClassLoader, url);
//java8Methodmethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);

util工具类

  • ArrayDeque 提供 resizable-array 并实现 Deque 接
  • Arrays 包含一个静态工厂,允许将数组视为列表
  • Collections 包含对集合进行操作或返回集合的静态方法
  • Date 表示特定的时间瞬间,精度为毫秒
  • Dictionary 是任何类的抽象父类,例如 Hashtable,它将键映射到值
  • EnumMap 一个专门用于枚举键的 Map 实现
  • EnumSet 一个专门用于枚举键的 Set 实现
  • Formatter 提供对布局对齐和对齐、数字、字符串和日期/时间数据的常用格式以及特定于语言环境的输出的支持
  • SecureRandom 实例用于生成安全的伪随机数流
  • UUID 表示一个不可变的通用唯一标识符
  • Vector 实现了一个可增长的对象数组

另见