title | toc | date | tags | |
---|---|---|---|---|
Java record |
true |
2018-07-12 |
|
记录在开发过程中遇到的java常见小问题、细节问题。
char[][] board
int n = board.length;
int m = n > 0 ? board[0].length : 0;
https://stackoverflow.com/questions/13832880/initialize-2d-array
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
按照第1个元素排序:
Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));
Arrays.sort(queries, Comparator.comparing(a -> a[0]));
Arrays.sort(queries, (a, b) -> a[0] - b[0]);
https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array
System.out.println(Arrays.toString(array));
Nested Array:
System.out.println(Arrays.deepToString(deepArray));
String.format("%06",12);//其中0表示补零而不是补空格,6表示至少6位
Integer.MIN_VALUE
和Integer.MAX_VALUE
使用
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
而不是
List<String> list = new ArrayList<String>();
...
String[] a = (String[]) list.toArray(list);
但是一下做法是错误的
List<Integer> list = new ArrayList<Integer>();
...
int[] a = list.toArray(new int[0]);
原因就在与int
不能作为范型类型参数(use int as a type argument for generics)。所以只能利用Java8的新特性了:
int[] array = list.stream().mapToInt(i->i).toArray();
https://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java
There is no shortcut for converting from int[]
to List<Integer>
as Arrays.asList
does not deal with boxing and will just create a List<int[]>
which is not what you want.
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int i : ints) intList.add(i);
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
clone方法是从Object类继承过来的,基本数据类型(String ,boolean,char,byte,short,float ,double,long)都可以直接使用clone方法进行克隆,注意String类型是因为其值不可变所以才可以使用。
int[] a1 = {1, 3};
int[] a2 = a1.clone();
public static native void arraycopy(Object src, int srcPos,
Object dest, int desPos, int length)
由于是native方法,所以效率非常高,在频繁拷贝数组的时候,建议使用。