import

import java.util.*;
import java.lang.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;

System

System.arraycopy(nums, 0, numsCopy, 0, nums.length);
Scanner in = new Scanner(System.in);
while (sc.hasNextLine()) {
    String word = in.nextLine();
    String[] inputs = word.split(" ");

    int N = Integer.valueOf(inputs[0]);
    int L = Integer.valueOf(inputs[1]);
}

Arrays工具类

[]  newArray = Arrays.copyOf([] original, int newLength)
Arrays.sort(int[]);
Arrays.sort(int[], 0, len);
Arrays.fill(int[], -1);
Arrays.asList(1, 2, 3);
List<Integer> triplet = Arrays.asList(new Integer[]{a, b, c});
List<List>.add(Arrays.asList(1, 2, 3));
List<Integer>.addAll(Arrays.asList(1, 2, 3))
Arrays.toString(new ArrayList<Integer>());

数组[]

int[] nums = new int[10];
nums.length;

Collections工具类

// sort the collection which implements the List interface, different from Arrays.sort(int[])
Collections.sort(new ArrayList<Integer>()); 

Collections.sort(ranges, (o1, o2) -> {
    if (o1.left != o2.left) {
        return o1.left - o2.left;
    }

    return o1.right - o2.right;
});
int loc = Collections.binarySearch(keys, key);

List

List<Integer> list = new ArrayList<>();
list.sort(Comparator.comparingInt(o -> o));
new ArrayList<>(list);

Iterator<Integer> it = list.iterator();
while (it.hasNext()) {}

Stack

Stack<Integer> stack = new Stack<>();
stack.isEmpty();
stack.push(1);
stack.pop();
stack.peek();

Queue

Queue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
Queue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
queue.offer()
queue.peek()
queue.poll()
Queue<Integer> queue = new PriorityQueue<>((o1, o2) -> countMap.get(o2) - countMap.get(o1));
Deque<Integer> deque = new LinkedList<>();

// Deque can serve as a stack
deque.push(2);
deque.pop();
deque.peekFirst();

// Deque can serve as a queue
deque.offer(4);
deque.poll();
deque.peekLast();

// Deque can serve as a double ended queue
deque.addFirst(1);
deque.addLast(1);
deque.removeFirst();
deque.removeLast();
deque.peek(); // read the first element in the list.

Set

Set<Integer> set = new HashSet<>();
set.add(1);
List<String> list = new ArrayList<>(set);
// sorted set
TreeSet<TreeNode> nodes = new TreeSet<>();

Map

Map<Integer, Queue<Integer>> map = new HashMap<>();
map.containsKey();
map.containsValue();

Set<String> keys = map.keySet();
// elements in the map are sorted by key
Map<String, Integer> words = new TreeMap<>();
// remain the order when elements are inserted in
Map<Character, Integer> countMap = new LinkedHashMap<>();

Comparator

Comparator<Integer> cmp = (o1, o2) -> o1 - o2;
Comparator<Integer> cmp = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1 - o2;
    }
};

String

Character c0 = (char) (int + 0);
Character[] letters = new Character[]{c0, c1, c2};
int dig = digits.charAt(idx) - '0';
char[] chars = s.toCharArray();
Arrays.sort(chars);
length()
isEmpty(), isBlank()
charAt()
getChars(), toCharArray()
getBytes()
equals(), hashCode() and equalsIgnoreCase()
contentEquals()
compareTo() and compareToIgnoreCase()
startsWith() and endsWith()
indexOf() and lastIndexOf()
substring() and subSequence()
concat()
matches()
replace(), replaceFirst(), and replaceAll()
contains()
split()
join()
toLowerCase() and toUpperCase()
trim(), strip(), stripLeading(), and stripTrailing()
lines()
indent()
transform()
format()
intern()
valueOf() and copyValueOf()
repeat()
describeConstable() and resolveConstantDesc()
formatted(), stripIndent(), and translateEscapes()
StringBuilder sb = new StringBuilder();
sb.append("1");

Integer

Integer i1 = new Integer(1);
Integer i2 = new Integer(2);
System.out.println(i1 > i2); // false, it will be properly processed by compiler and downgrade to primitive value
System.out.println(i1.intValue()); // return the primitive value

System.out.println(Integer.toBinaryString(15)); // 1111
System.out.println(Integer.toOctalString(15)); // 17
System.out.println(Integer.toHexString(15)); // f
System.out.println(Integer.valueOf("F", 16)); // 15

Math

min(), max()

Let's start with the simple methods :) Both functions take two numbers of any data type as parameters. min() returns the smallest number, max() returns the greatest one.

round(), ceil(), floor()

All three functions are related to rounding. round() takes a decimal number as parameter and returns the rounded number of the double data type in the way we learned in school (from 0.5 it rounds upwards, otherwise downwards). ceil() upwards and floor() rounds downwards no matter what.

We'll certainly be using round() very often. I practically used the other functions e.g. in determining the number of pages of a guestbook. When we've 33 comments and we print only 10 comments per page, they'll, therefore, occupy 3.3 pages. The result must be rounded up since there will be actually 4 pages.

abs() and signum()

Both methods take a number of any type as a parameter. abs() returns its absolute value and signum() returns a number based on its sign, -1, 0 or 1 (for a negative number, zero and a positive number).

sin(), cos(), tan()

Classic trigonometric functions, all take an angle as a double, which has to be entered in radians (not degrees if your country uses them). To convert degrees to radians we multiply them by * (Math.PI / 180). The return value is also a double.

acos(), asin(), atan()

Inverse trigonometric (arcus, sometimes cyclometric) functions, which return the original angle according to the trigonometric value. The parameter is a double and the returned angle is in radians (also as double). If we wish to have an angle in degrees, we have to divide the radians by / (180 / Math.PI).

pow() and sqrt()

pow() takes two double parameters. The first is the base of the power and the second is the exponent. If we wanted to calculate eg. 2^3, the code would be as following:

System.out.println(Math.pow(2, 3)); Sqrt is an abbreviation of SQuare RooT, which returns the square root of the number given as a double. Both functions return a double as the result.

exp(), log(), log()

exp() returns the Euler's number raised to a given exponent. log() returns the natural logarithm of a given number. log() returns the decadic logarithm of a number.

Hopefully, you noticed that the method list lacks any general root function. We, however, can calculate it using the functions the Math class provides.

We know that roots work like this: 3rd root of 8 = 8^(1/3). So we can write:

System.out.println(Math.pow(8, (1.0/3.0))); It's very important to write at least one number with a decimal point when we are dividing, otherwise, Java will assume that we want it to apply whole-number division, and the result would have been 8 ^ 0 = 1 in this case.

最大公约数

// max common divisor
public static int getMCD(int a, int b) {
    if (a % b == 0) {
        return b;
    }

    return getMCD(b, a % b);
}

// least common multiple
private int getLCM(int m, int n) {
    return m * n / getMCD(m, n);
}

Random

Random ran = new Random();
ran.nextInt(100); // [0, 99]

AtomicInteger

ReentrantLock

Lock lock = new ReentrantLock(true); // 公平锁, 按排队顺序获得锁
Condition conditionA = lock.newCondition();
Condition conditionB = rl.newCondition();

lock.lock();

test();

conditionB.signal();
conditionA.awaitUninterruptibly();

lock.unlock();

ReentrantReadWriteLock

private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

// 以下适合放在get()方法内
rwl.readLock().lock();
read();
rwl.readLock().unlock();

// 以下适合放在put()方法内
rwl.writeLock().lock();
write();
rwl.writeLock().unlock();

Semaphore

Semaphore semaphore = new Semaphore(20);
semaphore.acquire(5);// 获取5个许可,所以可运行线程数量为20/5=4
test();
semaphore.release(5);// 获取5个许可,所以可运行线程数量为20/5=4

CountDownLatch

CountDownLatch countDownLatch = new CountDownLatch(10);
test();
countDownLatch.countDown();
countDownLatch.await(); // 当第10个线程执行countDownLatch.countDown()后,当前语句不再阻塞

CyclicBarrier

CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
test();

 // 当有5个线程执行到当前语句时,当前语句不再阻塞
cyclicBarrier.await();

// 当有5个线程执行到当前语句时,当前语句不再阻塞,前提是在规定时间内,否则超时抛出异常
cyclicBarrier.await(300, TimeUnit.MICROSECONDS);

ForkJoinTask

static class QuickSortor extends RecursiveTask<Integer> {
    private int start;
    private int end;

    public QuickSortor(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        QuickSortor leftTask = new QuickSortor(start, left);
        QuickSortor rightTask = new QuickSortor(left + 1, end);

        leftTask.fork();
        rightTask.fork();

        leftTask.join();
        rightTask.join();
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 01:57:11

results matching ""

    No results matching ""