Using clone () vs new obj

I look at Cracking the Code Interview in this issue as well. I have to find all the paths in a binary tree that has the sum of a given number. I generally understand this code, but I wonder why the answer uses clone()instead of creating a new object with new?

public static void findSum(BinaryTreeNode root, int sum, ArrayList<Integer> buffer, int level) {
    // done parsing or empty tree
    if (root == null) {
        return;
    }
    int tmp = sum;
    buffer.add(root.value);
    for (int i = level; i >= 1; i--) {
        tmp -= buffer.get(i);
        if (tmp == 0) {
            print(buffer, i, level);
        }
    }
    ArrayList<Integer> c1 = (ArrayList<Integer>) buffer.clone();
    ArrayList<Integer> c2 = (ArrayList<Integer>) buffer.clone();
    findSum(root.left, sum, c1, level + 1);
    findSum(root.left, sum, c2, level + 1);
}

public static void print(ArrayList<Integer> bugger, int level, int i2) {
    for (int i = level; i <= i2; i++) {
        System.out.print(buffer.get(i) + " ");
    }
    System.out.println();
}
+4
source share
4 answers

This is a premature micro optimization due to the fact that cloning is a bit faster ( here is an answer with details on why cloning is faster for array lists ).

Cleaner Solution

ArrayList<Integer> c1 = new ArrayList<Integer>(buffer);

easier to understand, no coercion required, and this is unlikely to lead to any measurable performance difference.

+2

clone(). new ArrayList<Integer>(buffer) .

, . clone , , , .

+1

ArrayList . ( ) , , clone() Object. , , , , . , .

+1

newcreates an instance of a new object, and clone()looks more like a copy constructor. clone()The method creates a copy of the object with values member attributes also copied.

+1
source

Source: https://habr.com/ru/post/1524590/


All Articles