Java面试常用算法api速刷
数组
int[] arr1 = new int[5];
int[] arr2 = {1, 2, 3, 4, 5};
int[] arr3 = new int[]{3, 1, 2, 4, 5};
int[][] matrix1 = new int[3][3];
int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix3 = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
arr.length
Arrays.fill(arr1, 1);
Arrays.sort(arr3);
Arrays.copyOfRange(arr3, 1, 3);
List<Integer> list = Arrays.asList(arr); //list指向原数组位置
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); //List指向新数组位置
Integer[] newArray = list2.toArray(new Integer[0]);
String
String str1 = "Hello";
String str2 = new String("World");
str1.length()
str2.charAt(0)
str1.equals(str2)
str1.substring(1, 3) //起始位置,最终位置,左闭右开
str1.indexOf("ll")
str1.lastIndexOf("l")
str1.toUpperCase()
str1.toLowerCase()
str1.replace("l", "p")
String[] split = "a,b,c".split(",");
str.trim()
char[] charArray = str1.toCharArray();
StringBuilder
StringBuilder sb = new StringBuilder();
sb.append(str1).append(str2);
sb.reverse().toString()
sb.insert(4, "insert");
sb.replace(4, 10, "java"); //起始位置,最终位置,左闭右开
sb.reverse();
sb.substring(1,3) //起始位置,最终位置,左闭右开
sb.setCharAt(1, 'T');
sb.length()
sb.charAt(1)
sb.toString()
集合通用:
size()
clear()
isEmpty()
ArrayList
List<String> arrayList = new ArrayList<>();
List<String> arrayList1 = new ArrayList<>(Arrays.asList("1", "2", "3"));
arrayList.add("4");
arrayList.get(0);
arrayList.set(0, "10");
arrayList.remove("2");
arrayList.remove(0);
arrayList.contains("3")
arrayList.size()
arrayList1.clear();
// 迭代器遍历List
Iterator<String> iterator = linkedList1.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
HashSet
Set<String> hashSet = new HashSet<>();
Set<String> hashSet1 = new HashSet<>(Arrays.asList("1", "2", "3"));
hashSet1.add("4");
hashSet1.remove("4");
hashSet1.contains("3")
hashSet1.size()
hashSet1.clear();
HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "1");
hashMap.put(2, "2");hashMap.remove(2);
hashMap.get(1);
// 遍历键
for (Integer key : hashMap.keySet()) {
System.out.println("key: " + key);
}
// 遍历值
for (String val : hashMap.values()) {
System.out.println("value: " + val);
}
ArrayDeque
Deque<Integer> arrayDeque = new ArrayDeque<>();
arrayDeque.peek();
arrayDeque.offerFirst(2);
arrayDeque.offerLast(12);
arrayDeque.offer(13); //跟末尾插入一样
arrayDeque.pollFirst();
arrayDeque.pollLast();
arrayDeque.poll(); //跟末尾弹出一样//当栈用
arrayDeque.peek();
arrayDeque.pop();
arrayDeque.push();
PriorityQueue
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(1);
priorityQueue.poll()priorityQueue.peek()
PriorityQueue<Integer> priorityQueue1 = new PriorityQueue<>((a, b) -> b - a);
priorityQueue1.offer(1);
Scanner工具类
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
String str = scanner.next(); // 读取下一个字符串(到空格为止)
scanner.nextLine(); // 读取换行符,避免影响下一次读取
String str = scanner.nextLine(); // 获取用户输入的字符串
scanner.close(); // 关闭 Scanner 对象
boolean hasNext()
:检查输入流是否还有下一个标记。boolean hasNextLine()
:检查输入流是否还有下一行。