Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Last active May 24, 2020 23:44
Show Gist options
  • Save junminstorage/6699f3941c577f4b577d5bd5888db00d to your computer and use it in GitHub Desktop.
Save junminstorage/6699f3941c577f4b577d5bd5888db00d to your computer and use it in GitHub Desktop.
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
@junminstorage
Copy link
Author

junminstorage commented May 11, 2020

pq comparator construction function, sorted by distance then sorted by x-coordinate:

Or

 PriorityQueue<int[]> pq  = new PriorityQueue<>(K+1, (p1, p2) -> { 
    int diff = dist(p1[0], p1[1]) - dist(p2[0], p2[1]); //sort by distance
    if(diff == 0) return p1[0] - p2[0];  //then sort by x-coordinate 
    else return diff;
});

Or

PriorityQueue<int[]> pq  = new PriorityQueue<>(K+1, Comparator.comparing((int[] p)->dist(p[0], p[1])).reversed().comparing(p->p[0]) );

@junminstorage
Copy link
Author

junminstorage commented May 24, 2020

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