EzDevInfo.com

clone interview questions

Top clone frequently asked interview questions

How do I clone a generic List in Java?

I have an ArrayList<String> that I'd like to return a copy of. ArrayList has a clone method has the following signature:

public Object clone()

After I call this method, how do I cast the returned Object back to ArrayList<String>?


Source: (StackOverflow)

What is the best way to clone/deep copy a .NET generic Dictionary?

I've got a generic dictionary Dictionary that I would like to essentially make a Clone() of ..any suggestions.


Source: (StackOverflow)

Advertisements

What do these words mean in Git: Repository, fork, branch, clone, track?

I'm honestly not clear on the semantics here. They're all about copies/variants of a code+history unit, but past that I'm not sure I could say. Is this logical structure explained somewhere?


Source: (StackOverflow)

How to properly override clone method?

I need to implement a deep clone in one of my objects which has no superclass.

What is the best way to handle the checked CloneNotSupportedException thrown by the superclass (which is Object)?

A coworker advised me to handle it the following way:

@Override
public MyObject clone()
{
    MyObject foo;
    try
    {
        foo = (MyObject) super.clone();
    }
    catch (CloneNotSupportedException e)
    {
        throw new Error();
    }

    // Deep clone member fields here

    return foo;
}

This seems like a good solution to me, but I wanted to throw it out to the StackOverflow community to see if there are any other insights I can include. Thanks!


Source: (StackOverflow)

Shallow copy of a Map in Java

As I understand it, there are a couple of ways (maybe others as well) to create a shallow copy of a Map in Java:

Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> shallowCopy;

// first way
shallowCopy = new HashMap<String, Object>(data);

// second way
shallowCopy = (Map<String, Object>) ((HashMap<String, Object>) data).clone();

Is one way preferred over the other, and if so, why?

One thing worth mentioning is that the second way gives an "Unchecked Cast" warning. So you have to add @SuppressWarnings("unchecked") to get around it, which is a little irritating (see below).

@SuppressWarnings("unchecked")
public Map<String, Object> getDataAsMap() {
    // return a shallow copy of the data map
    return (Map<String, Object>) ((HashMap<String, Object>) data).clone();
}

Source: (StackOverflow)

How do I create a copy of an object in PHP?

It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.

Here's a simple, contrived proof:

<?php

class A {
    public $b;
}


function set_b($obj) { $obj->b = "after"; }

$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.

set_b($a);

print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'

?>

In both print cases I am getting 'after'

So, how do I pass $a to *set_b()* by value, not by reference?


Source: (StackOverflow)

Clone() vs Copy constructor- which is recommended in java [duplicate]

This question already has an answer here:

clone method vs copy constructor in java. which one is correct solution. where to use each case?


Source: (StackOverflow)

How do you clone a BufferedImage

Hi I have an object which has many bufferedimages in it, I want to create a new object copying all the bufferedimages into the new object, but these new images may be altered and i dont want the original object images to be altered by altering the new objects images.

is that clear?

Is this possible to do and can anyone suggest a good way to do it please? I have thought of getSubImage but read somewhere that any changes to the subimage are relected back to the parent image.

I just want to be able to get a fresh entirely seperate copy or clone of a BufferedImage

chris wade


Source: (StackOverflow)

console.log object at current state

console.log will show the object at the last state of execution, not at the state when console.log was called.

I have to clone the object just to output it via console.log to get the state of the object at that line.

How can I change the default behavior of console.log? (Error console in safari, no add-on)

Example:

var test = {a: true}
console.log(test); // {a: false}
test.a = false; 
console.log(test); // {a: false}

Source: (StackOverflow)

How to clone an InputStream?

I have a InputStream that I pass to a method to do some processing. I will use the same InputStream in other method, but after the first processing, the InputStream appears be closed inside the method.

How I can clone the InputStream to send to the method that closes him? There is another solution?

EDIT: the methods that closes the InputStream is an external method from a lib. I dont have control about closing or not.

private String getContent(HttpURLConnection con) {
    InputStream content = null;
    String charset = "";
    try {
        content = con.getInputStream();
        CloseShieldInputStream csContent = new CloseShieldInputStream(content);
        charset = getCharset(csContent);            
        return  IOUtils.toString(content,charset);
    } catch (Exception e) {
        System.out.println("Error downloading page: " + e);
        return null;
    }
}

private String getCharset(InputStream content) {
    try {
        Source parser = new Source(content);
        return parser.getEncoding();
    } catch (Exception e) {
        System.out.println("Error determining charset: " + e);
        return "UTF-8";
    }
}

Source: (StackOverflow)

The difference between fork(), vfork(), exec() and clone()

I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls.

I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ?

Fork : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible).

The new process (child) gets a different process ID (PID) and has the the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code.

Vfork : The basic difference between vfork and fork is that when a new process is created with vfork(), the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls execve(), at which point the parent process continues.

This means that the child process of a vfork() must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the vfork() call, and it must not call exit() (if it needs to exit, it should use _exit(); actually, this is also true for the child of a normal fork()).

Exec : The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. exec() replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an exec() error.

Clone : Clone, as fork, creates a new process. Unlike fork, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers.

When the child process is created with clone, it executes the function application fn(arg). (This differs from for, where execution continues in the child from the point of the fork call.) The fn argument is a pointer to a function that is called by the child process at the beginning of its execution. The arg argument is passed to the fn function.

When the fn(arg) function application returns, the child process terminates. The integer returned by fn is the exit code for the child process. The child process may also terminate explicitly by calling exit(2) or after receiving a fatal signal.

Information gotten form :

Thanks for taking the time to read this ! :)


Source: (StackOverflow)

Why is the clone() method protected in java.lang.Object?

What is the specific reason that clone() is defined as protected in java.lang.Object?


Source: (StackOverflow)

Java: recommended solution for deep cloning/copying an instance

I'm wondering if there is a recommended way of doing deep clone/copy of instance in java.

I have 3 solutions in mind, but I can have miss some, and I'd like to have your opinion

edit: include Bohzo propositon and refine question: it's more about deep cloning than shallow cloning.

Do it yourself:

code the clone by hand properties after properties and check that mutable instances are cloned too.
pro:
- control of what will be performed
- quick execution
cons:
- tedious to write and maintain
- bug prone (copy/paste failure, missing property, reassigned mutable property)

Use reflection:

With your own reflection tools or with an external helper (like jakarta common-beans) it is easy to write a generic copy method that will do the job in one line.
pro:
- easy to write
- no maintenance
cons:
- less control of what happens
- bug prone with mutable object if the reflection tool does not clone sub objects too
- slower execution

Use clone framework:

Use a framework that do it for you, like :
commons-lang SerializationUtils
Java Deep Cloning Library
Dozer
Kryo

pro:
- same as reflection
- more control over what will be exactly be cloned.
cons:
- every mutable instance is fully cloned, even at the end of the hierarchy
- could be very slow to execute

Use bytecode instrumentation to write clone at runtime

javassit, BCEL or cglib might be use to generate a dedicated cloner as fast as one hand writed. Someone knows a lib using one of these tools for this purpose ?

What I have missed here ?
Which one would you recommend ?

Thanks.


Source: (StackOverflow)

What's the difference between Ruby's dup and clone methods?

The Ruby docs for dup say:

In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.

But when I do some test I found they are actually the same:

class Test
   attr_accessor :x
end

x = Test.new
x.x = 7
y = x.dup
z = x.clone
y.x => 7
z.x => 7

So what are the differences between the two methods?


Source: (StackOverflow)

How do I copy an object in Java?

Consider the below code:

DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'

DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'

dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'

So, I want to copy the 'dum' to 'dumtwo' and I want to change 'dum' without affecting the 'dumtwo'. But the above code is not doing that. When I change something in 'dum', the same change is happening in 'dumtwo' also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of 'dum' and assign it to 'dumtwo'?


Source: (StackOverflow)