Last active
May 24, 2020 23:44
-
-
Save junminstorage/6699f3941c577f4b577d5bd5888db00d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<int[]> list = new ArrayList<>(); | |
list.add(new int[]{1, 2}); | |
list.add(new int[]{2, 3}); | |
int[][] re = list.toArray(new int[2][0]); //THIS MAY HAVE BUG IF list.size is not 2 |
JDK ArrayList.toArray source code
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size) <== if we provide a.length > list.size(), then it will fill in null value at index of size
a[size] = null;
return a;
}
So correct way to convert list to array is to provide empty array in toArray() method:
final List<int[]> list = new ArrayList<>();
list.add(new int[]{1, 2});
int[][] re = list.toArray(new int[0][0]); //THIS IS CORRECT
out.println(re.length == list.size()); // output: true
re = list.toArray(new int[2][0]); //THIS IS WRONG
out.println(re.length != list.size()); //output: true
out.println(re.length == 1); //output: false
list.add(new int[]{2, 3});
re = list.toArray(new int[0][0]);
out.println(re.length == list.size()); //output: true
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pq comparator construction function, sorted by distance then sorted by x-coordinate:
Or
Or