Rectangle 27 1

what about b, the object that is passed in? 
Will its fields/data members be modified as well?

Since java by default is pass-by-value, object that is passed in the contructor is pass-by-value but its internally its fields within that object will have reference, therefore when you call bofA.mutator() the B b field will change as well.

To have deep copy you need to copy each of the field in the b object that was passed and use Arrays.copyOf().

In Java, are fields of array type deep copied or shallow copied? - Sta...

java arrays deep-copy shallow-copy
Rectangle 27 16

Right now, you can't use the initializer list for array members. You're stuck doing it the hard way.

In C++0x you can write:

class Baz {
    Foo foo[3];

    Baz() : foo({4, 5, 6}) {}
};

interesting... I probably should have used something besides int then in my example, as it's too "easy" to deal with. :-)

C++: constructor initializer for arrays - Stack Overflow

c++ constructor initializer
Rectangle 27 48

Unfortunately, you're right. +1 Note that C++1x' unified initialization syntax will allow you to do this.

@sbi: I still call it "C++0x". Of course, I also sometimes give my age as 38, and hope to retire at the age of 3E.

@David: I call it C++1x (hoping it will be released within the next 9.5 years).

The committee continues to use C++0X. I though I had seen a rational for that but I'm currently unable to find it.

C++: constructor initializer for arrays - Stack Overflow

c++ constructor initializer
Rectangle 27 22

The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.

As an example, let's say you have a person class:

class Person {
    String name;
    List<String> emailAddresses
}

How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses in the new object. But if you modified the contents of the emailAddresses list, you would be modifying the list in both copies (since that's how object references work).

A deep copy would mean that you recursively copy every member, so you would need to create a new List for the new Person, and then copy the contents from the old to the new object.

Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.

+1 for nice answer but what about this "reference to emailAddresses" Really? because i feel emailAddresses itself is reference.

it's like "reference to reference" in saying "reference to emailAddresses" which is nothing. i understood what you are trying to say but it can confuses few people.and our answers shouldn't trouble few people also :)

java - Deep copy, shallow copy, clone - Stack Overflow

java clone
Rectangle 27 22

The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.

As an example, let's say you have a person class:

class Person {
    String name;
    List<String> emailAddresses
}

How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses in the new object. But if you modified the contents of the emailAddresses list, you would be modifying the list in both copies (since that's how object references work).

A deep copy would mean that you recursively copy every member, so you would need to create a new List for the new Person, and then copy the contents from the old to the new object.

Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.

+1 for nice answer but what about this "reference to emailAddresses" Really? because i feel emailAddresses itself is reference.

it's like "reference to reference" in saying "reference to emailAddresses" which is nothing. i understood what you are trying to say but it can confuses few people.and our answers shouldn't trouble few people also :)

java - Deep copy, shallow copy, clone - Stack Overflow

java clone
Rectangle 27 13

A list (in CPython) is an array at least as long as the list and up to twice as long. If the array isn't full, appending to a list is just as simple as assigning one of the array members (O(1)). Every time the array is full, it is automatically doubled in size. This means that on occasion an O(n) operation is required, but it is only required every n operations, and it is increasingly seldom required as the list gets big. O(n) / n ==> O(1). (In other implementations the names and details could potentially change, but the same time properties are bound to be maintained.)

Appending to a list already scales.

Is it possible that when the file gets to be big you are not able to hold everything in memory and you are facing problems with the OS paging to disk? Is it possible it's a different part of your algorithm that doesn't scale well?

Thanks for clarifying ~ so once in a while, I have an O(n) operation, but the next time the loop happens, it is back to the usual? I will do a detailed timing analysis of my code in the next few days and post again.

Yes, the O(n) operations only occur occasionally. The number of appends between them grows at the same rate as n, so it averages out to having only a constant effect.

256 GIGABYTES of ram or 128 or 64 but nothing lower than 64 GIGABYTES. For example: top - 02:36:31 up 36 days, 11:21, 7 users, load average: 0.84, 0.31, 0.11 Tasks: 274 total, 2 running, 272 sleeping, 0 stopped, 0 zombie Cpu(s): 6.2%us, 0.1%sy, 0.0%ni, 93.8%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 132370600k total, 7819100k used, 124551500k free, 481084k buffers Swap: 2031608k total, 3780k used, 2027828k free, 5256144k cached

Thanks Mike ~ below you mention that turning gc off helped you ~ is there any side effects to that? When should I turn it back on?

class - Is there a way to circumvent Python list.append() becoming pro...

python class list performance append
Rectangle 27 6

In a few important cases, assignability is simply not needed. These are often lightweight algorithm wrappers that facilitate calculation without leaving the scope. Such objects are prime candidates for reference members since you can be sure that they always hold a valid reference and never need to be copied.

In such cases, make sure to make the assignment operator (and often also the copy constructor) non-usable (by inheriting from boost::noncopyable or declaring them private).

However, as user pts already commented, the same is not true for most other objects. Here, using reference members can be a huge problem and should generally be avoided.

c++ - Should I prefer pointers or references in member data? - Stack O...

c++ reference class-members
Rectangle 27 6

In a few important cases, assignability is simply not needed. These are often lightweight algorithm wrappers that facilitate calculation without leaving the scope. Such objects are prime candidates for reference members since you can be sure that they always hold a valid reference and never need to be copied.

In such cases, make sure to make the assignment operator (and often also the copy constructor) non-usable (by inheriting from boost::noncopyable or declaring them private).

However, as user pts already commented, the same is not true for most other objects. Here, using reference members can be a huge problem and should generally be avoided.

c++ - Should I prefer pointers or references in member data? - Stack O...

c++ reference class-members
Rectangle 27 2

Try following query. It's fetching documents where status is not equals to "finished"

Note: This query will work with MongoDB 3.2+ only

db.collection.aggregate([
    {
      $project:{
        "projectid" : 1,
        "campname" : 1,
        "campstatus" : 1,
        "clientid" : 1,
        "paymentreq" : 1,
        products:{
          $filter:{
            input:"$products", 
            as: "product", 
            cond:{$ne: ["$$product.status", "finished"]}
           }
        }
      }
    },
    {
      $match:{"products":{$gt: [0, {$size:"products"}]}}
    }
])

Unfortunately, it will only check if the first object of the products array have a field status that does not equal "finished". I ran the query in a collection that contains a document with two products where only one has the status "finished" and it did not returned the document. All products in the array must have a status of "finished" for the query to ignore the document. Huh, this is so complicated.

Well this is the reason I asked you to update a real document sample with multiple products. Posting schema is not enough. Also mention your MongoDB version too.

Got the following error : Failed to parse: filter: [ { $project: { products: { $filter: { input: \"$products\", as: \"product\", cond: { $ne: [ \"$$product.status\", \"finished\" ] } } } } } ]. 'filter' field must be of BSON type Object.

javascript - Match Documents where all array members do not conatin a ...

javascript mongodb mongodb-query aggregation-framework
Rectangle 27 10

  • If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well.
  • Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects.

ICloneable doesn't have a generic interface, so it is not recommended to use that interface.

c# - Deep cloning objects - Stack Overflow

c# .net clone
Rectangle 27 10

  • If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well.
  • Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects.

ICloneable doesn't have a generic interface, so it is not recommended to use that interface.

c# - Deep cloning objects - Stack Overflow

c# .net clone
Rectangle 27 1

It is necessary to override clone() if class B defines non-primitve mutable member fields. These need to be deep copied explicitly within B.clone(). If B only contains primitive and/or immutable data members, A.clone() will do the job.

If you're calling super.clone in every clone implementation, then you'll eventually call Object#clone. And that method will make shallow copy of all data fields. I think, OP has got it right.

@Nikita, the first version of my answer was incorrect indeed, but I have since updated it, now I believe it is right.

If any of B's ancestors define clone in terms of a copy constructor rather than in terms of Object, then B must do likewise. If B uses a copy constructor even though all its ancestors chain to base.clone, it compels all of its descendents to likewise use a copy constructor. Personally, I find irksome the notion of clone methods that do anything other than chaining to base.clone, but such methods are alas very common.

java - Does subclass need to override Clone() method explicitly if sup...

java clone
Rectangle 27 15

The short answer is you inherit from the ICloneable interface and then implement the .clone function. Clone should do a memberwise copy and perform a deep copy on any member that requires it, then return the resulting object. This is a recursive operation ( it requires that all members of the class you want to clone are either value types or implement ICloneable and that their members are either value types or implement ICloneable, and so on).

For a more detailed explanation on Cloning using ICloneable, check out this article.

The long answer is "it depends". As mentioned by others, ICloneable is not supported by generics, requires special considerations for circular class references, and is actually viewed by some as a "mistake" in the .NET Framework. The serialization method depends on your objects being serializable, which they may not be and you may have no control over. There is still much debate in the community over which is the "best" practice. In reality, none of the solutions are the one-size fits all best practice for all situations like ICloneable was originally interpreted to be.

See the this Developer's Corner article for a few more options (credit to Ian).

ICloneable doesn't have a generic interface, so it is not recommended to use that interface.

Your solution works until it needs to handle circular references, then things start to complicate, it's better to try implement deep cloning using deep serialization.

Unfortunately, not all objects are serializable either, so you can't always use that method either. Ian's link is the most comprehensive answer so far.

c# - Deep cloning objects - Stack Overflow

c# .net clone
Rectangle 27 15

The short answer is you inherit from the ICloneable interface and then implement the .clone function. Clone should do a memberwise copy and perform a deep copy on any member that requires it, then return the resulting object. This is a recursive operation ( it requires that all members of the class you want to clone are either value types or implement ICloneable and that their members are either value types or implement ICloneable, and so on).

For a more detailed explanation on Cloning using ICloneable, check out this article.

The long answer is "it depends". As mentioned by others, ICloneable is not supported by generics, requires special considerations for circular class references, and is actually viewed by some as a "mistake" in the .NET Framework. The serialization method depends on your objects being serializable, which they may not be and you may have no control over. There is still much debate in the community over which is the "best" practice. In reality, none of the solutions are the one-size fits all best practice for all situations like ICloneable was originally interpreted to be.

See the this Developer's Corner article for a few more options (credit to Ian).

ICloneable doesn't have a generic interface, so it is not recommended to use that interface.

Your solution works until it needs to handle circular references, then things start to complicate, it's better to try implement deep cloning using deep serialization.

Unfortunately, not all objects are serializable either, so you can't always use that method either. Ian's link is the most comprehensive answer so far.

c# - Deep cloning objects - Stack Overflow

c# .net clone
Rectangle 27 13

For simple array members like that, you can use JSON.parse.

var array = JSON.parse("[" + string + "]");
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";

var array = JSON.parse("[" + listValues + "]");

This gives you an Array of numbers.

[0, 1]
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes

If you use .split(), you'll end up with an Array of strings.

["0", "1"]

Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.

If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.

var array = string.split(",").map(Number);

Also be aware that JSON.parse(); is not available in IE6, IE7. I think in this case the String.split(','); is easier.

@scunliffe: True, a shim would be needed, or one could take the jQuery approach to shim it var array = (new Function("return [" + string + "];"))(). Using .split() is alright if Numbers aren't needed, otherwise you'd need to map the result.

@Downvoter: Try to describe what is wrong with the answer so that I can demonstrate how you're wrong.

eval()

javascript - Convert string with commas to array - Stack Overflow

javascript arrays string
Rectangle 27 79

// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}
var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

+1 for taking into account things like Date and RegExp, which neither jQuery nor Underscore do

var obj = {}
obj.a = obj

I don't understand this function. Suppose from.constructor is Date for example. How would the third if test be reached when the 2nd if test would succeed & cause the function to return (since Date != Object && Date != Array)?

@AdamMcKee Because javascript argument passing and variable assignment is tricky. This approach works great, including dates (which indeed are handled by the second test) - fiddle to test here: jsfiddle.net/zqv9q9c6.

@NickSweeting: Try - may be it works. If not - fix it and update the answer. That's how it works here in community:)

What is the most efficient way to deep clone an object in JavaScript? ...

javascript object clone
Rectangle 27 76

// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}
var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

+1 for taking into account things like Date and RegExp, which neither jQuery nor Underscore do

var obj = {}
obj.a = obj

I don't understand this function. Suppose from.constructor is Date for example. How would the third if test be reached when the 2nd if test would succeed & cause the function to return (since Date != Object && Date != Array)?

@AdamMcKee Because javascript argument passing and variable assignment is tricky. This approach works great, including dates (which indeed are handled by the second test) - fiddle to test here: jsfiddle.net/zqv9q9c6.

@NickSweeting: Try - may be it works. If not - fix it and update the answer. That's how it works here in community:)

What is the most efficient way to deep clone an object in JavaScript? ...

javascript object clone
Rectangle 27 76

// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}
var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

+1 for taking into account things like Date and RegExp, which neither jQuery nor Underscore do

var obj = {}
obj.a = obj

I don't understand this function. Suppose from.constructor is Date for example. How would the third if test be reached when the 2nd if test would succeed & cause the function to return (since Date != Object && Date != Array)?

@AdamMcKee Because javascript argument passing and variable assignment is tricky. This approach works great, including dates (which indeed are handled by the second test) - fiddle to test here: jsfiddle.net/zqv9q9c6.

@NickSweeting: Try - may be it works. If not - fix it and update the answer. That's how it works here in community:)

What is the most efficient way to deep clone an object in JavaScript? ...

javascript object clone
Rectangle 27 76

// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}
var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

+1 for taking into account things like Date and RegExp, which neither jQuery nor Underscore do

var obj = {}
obj.a = obj

I don't understand this function. Suppose from.constructor is Date for example. How would the third if test be reached when the 2nd if test would succeed & cause the function to return (since Date != Object && Date != Array)?

@AdamMcKee Because javascript argument passing and variable assignment is tricky. This approach works great, including dates (which indeed are handled by the second test) - fiddle to test here: jsfiddle.net/zqv9q9c6.

@NickSweeting: Try - may be it works. If not - fix it and update the answer. That's how it works here in community:)

What is the most efficient way to deep clone an object in JavaScript? ...

javascript object clone
Rectangle 27 76

// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}
var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

+1 for taking into account things like Date and RegExp, which neither jQuery nor Underscore do

var obj = {}
obj.a = obj

I don't understand this function. Suppose from.constructor is Date for example. How would the third if test be reached when the 2nd if test would succeed & cause the function to return (since Date != Object && Date != Array)?

@AdamMcKee Because javascript argument passing and variable assignment is tricky. This approach works great, including dates (which indeed are handled by the second test) - fiddle to test here: jsfiddle.net/zqv9q9c6.

@NickSweeting: Try - may be it works. If not - fix it and update the answer. That's how it works here in community:)

What is the most efficient way to deep clone an object in JavaScript? ...

javascript object clone