Liondancer
Liondancer

Reputation: 16489

using clone() vs new obj

I am looking over Cracking the Code Interview and in this problem. I am supposed to find all paths in a binary tree that has the sum of a given number. I generally understand this code but I am wondering 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();
}

Upvotes: 4

Views: 121

Answers (4)

Kick
Kick

Reputation: 4923

new operator instantiates the new object while clone() is more like a copy constructor. clone() method creates a copy of the object with values of member attributes also copied.

Upvotes: 1

ucsunil
ucsunil

Reputation: 7504

You could create a new ArrayList object and achieve the same results. A good programming practice (although not necessarily applicable to this situation) is to work with copies of the original objects and clone() provides this all the time through implicit inheritance from the Object class. So a possible reason they used clone is because it is the most commonly used methods to duplicate an object. When you think about it, it is a bit more compact.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

This is a premature micro-optimization, attributed to the fact that cloning goes a little faster (here is an answer with the details on why cloning is faster for array lists).

A solution with the cleaner-looking

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

is easier to understand, does not require a cast, and it it unlikely to cause any measurable performance difference.

Upvotes: 2

tbodt
tbodt

Reputation: 17017

There is really no reason to prefer clone() in this circumstance. new ArrayList<Integer>(buffer) would also work just as well.

But the situation may not be the same for classes other than collections. clone is usually used when there is no constructor that duplicates an object, but a duplicate is desired anyway.

Upvotes: 1

Related Questions