Clone() and object copys

I have been reading about String and arrays and trying to understand the difference between clone() and system.arraycopy..... Here are my questions regarding this:
1. Why isn't there a deep copy for String, especially if we all need to keep writing code to make up for it?
2. What happens when using the assignment operator for a non-array object, say String? Is it getting a reference, or new memory with a copy of the values? eg.
String strThis= "Hello Java";
String strNew = strThis;

I have been reading about String and arrays and trying
to understand the difference between clone() and
system.arraycopy..... Look at the arguments for each method and read the JavaDoc - clone creates an object, whereas arraycopy copies a subarray to an existing subarray.
Here are my questions regarding
this:
1. Why isn't there a deep copy for String, especially
if we all need to keep writing code to make up for
it?Sting objects are immutable, so what would you gain from a deep copy? What code do "we all need to keep writing to make up for it"?
2. What happens when using the assignment operator for
a non-array object, say String? Is it getting a
reference, or new memory with a copy of the values?
eg.
String strThis= "Hello Java";
String strNew = strThis;It gets a copy of the reference.

Similar Messages

  • Is it possible to clone an object from one image and paste it on another image?

    Is it possible to clone an object from one image and paste it on another image in Aperture?

    As Frank said,
    but Aperture has a nice clone tool - the drawback is, that it only works within one image.
    What I sometimes do - as a workaroud, when I want to use the clone brush, is to combine the image I want to clone from and the image I want to clone into, into one single image by printing them together to pdf as jpeg. Then I can clone from the second to the first, for example, to be able to add an fairy to a flower: Picking up the head of the fairy in the right image and brushing it into the left one. Occasionally I prefer the Aperture brush to the Photoshop lasso.

  • Clone an Object

    Hey everyone,
    I just had a question about cloning an object.
    I have an object and within that object there is a field that holds a "date".
    I want to clone the object x number of times (x is user input) and each clone the "date" is the next day.
    So the second clone's "date" value would be the next day after the first clone's "date" value. I also want each clone stored into an array of that object.
    I have a date class and within that date class is a method called "nextDay" which changes the date to the next day.
    I hope that makes sense.
    Anyways, the way I went about it was this:
    Object original = new Object();
    drawCount = user input;
    Object[] array = new Object[drawCount];
    array[0] = original;
    if(drawCountInt > 1)
         for(int j = 1;j <= drawCountInt;j++)
            Object daClone = (Object) original.clone;
            daClone.date = daClone.date.nextDay();
    }Now that seems like it would work once.
    I am trying to figure out, how would I increment the date in a loop?
    I could not figure out a way to use the counter to maybe make the nextDay happen more often.
    I could not also find a way to make a clone of a clone inside a loop and just use the nextDay on that.
    How would I make a clone off the latest clone inside a for or while loop?
    Sorry if any of this seems a little unclear. Feel free to ask questions of course.

    So something like this then?
    if(drawCountInt > 1)
    {     Array[1] = (Object) original.clone;
             for(int j = 1;j <= drawCount;j++)
                       Array[j] = (Objectt) Array[j].clone;
                       Array[j].date = Array[j].date.nextDay();
    }

  • Why clone() in Object Class is protected

    hi,
    Why clone() in Object Class is protected
    Why finalize() in Object Class is protected
    Waiting for your reply
    suresh

    Why clone() in Object Class is protectedObject's clone() is meant to provide a generic cloning facility as the assistance for the types implementing Cloneable but not as a public ready-made method. Object's clone() should be overridden for those types to provide a meaningful implementation (maybe relying on Object's clone). Object's clone() being public were an invitation to try to clone every object, regardless of its being cloneable or not. For a type to be cloneable, it is necesary for this type in implement Cloneable, a no-method interface. While at writing the class and declaring it as Cloneable, it is not much more work to provide a clone() implementation. It is the responsibility of the author of a class to decide whether it should be cloneable and if yes, how it should be cloned.
    Why finalize() in Object Class is protected"finalize" is meant for the VM to invoke is as defined by the specification.
    Encapsulation implies everything should have the smallest scope, the most restrictve access which is still appropriate.

  • Is this write way to clone a object?

    All,
    I this the correct way to clone a object? if not so can anyone point me the right way to do that. Because this method is taking longer time to execute.
    import java.io.*;
    public class ObjectCloner
        public ObjectCloner()
        public static Object clone(Object obj)
            throws Exception
            ByteArrayOutputStream bstream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bstream);
            out.writeObject(obj);
            out.close();
            ByteArrayInputStream binstream = new ByteArrayInputStream(bstream.toByteArray());
            ObjectInputStream oin = new ObjectInputStream(binstream);
            Object newobj = oin.readObject();
            return newobj;
        public static int sizeOf(Object obj)
            try
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bstream);
                out.writeObject(obj);
                out.close();
                return bstream.toByteArray().length;
            catch(Exception ex)
                ex.printStackTrace();
            return 0;
    }

    calvino_ind wrote:
    i might be wrong, but i think there are some really easier ways to clone an object:
    public class Age {
    int numberOfYears;
    public Age(int numberOfYears) {
    this.numberOfYears = numebrOfYears;
    public Object clone() {
    return new Age(this.numberOfYears);
    No! This is very wrong. For this simple example, all one needs is class Age to implement Cloneable and
    public Object clone() {
             return super.clone();
    }which will automatically give you a shallow clone of the the class.
    Consider what ill happen with your approach when one clones superclasses of class Age.
    Edited by: sabre150 on May 26, 2008 3:42 PM

  • What is the need to clone  an object

    What is the need to clone an object
    give me the scenarios where we use cloneable interface

    In a very simple statements,
    clone method will return the new object with the
    SAME SOURCE STATE. Where as
    creating an object using "new" will give completely
    new object.According to whom? I was under the impression that the state of the object returned by calling close was not defined except from what is returned by the Object class.
    As for clone being faster than constructors, it can be. It depends on what the constructor does. For instance, I'm sure its faster to clone an ArrayList than to create a new one by passing the old one into its constructor. Depends on the implementation of the constructor vs. the implementation of the clone.
    Again, do not expose clone because its behavior is not defined. Create an interface with a methd on it, and define what that method returns. Then use clone to create your base object to construct the copy to return.

  • How to Clone  inherited Object ?

    According to the rule of cloning a object can be cloned only if
    it implements Cloneable interface ? In the following example
    class B extends class A which does not implement Cloneable interface,class B does implement Cloneable interface.
    when I try to clone an object of class A in class B it is very
    allowing to be cloned which is a contradictary?Please go through the
    example and suggest what is wrong ?
    class A
    int v = 100;
    public Object Clone()
    return new A();
    class B extends A implements Cloneable
    public static void main(String args[])
    A a = new A();
    A b = null;
    b = (A)a.clone();
    System.out.println("Value of v1 :" +a.v1);
    System.out.println("Value of v1 :" +b.v1);
    Thanks for your valuable help

    According to the rule of cloning a object can be
    cloned only if
    it implements Cloneable interface ? In the following
    example
    class B extends class A which does not implement
    Cloneable interface,class B does implement Cloneable
    interface.
    when I try to clone an object of class A in class B it
    is very
    allowing to be cloned which is a contradictary?Please
    go through the
    example and suggest what is wrong ?
    class A
    int v = 100;
    public Object Clone()
    return new A();
    class B extends A implements Cloneable
    public static void main(String args[])
    A a = new A();
    A b = null;
    b = (A)a.clone();
    System.out.println("Value of v1 :" +a.v1);
    System.out.println("Value of v1 :" +b.v1);
    Thanks for your valuable helpApart the fact that like that program cannot function, you didn't clone anything. You've just created another instance of class A!
    Cloning means to create a copy of an existing object with aonother one having exact members (name, value, behaviour) like the first one!
    Try to replace this piece of code:
    A a = new A();
    a.v = 500;
    A b = null;
    b = (A)a.clone();
    System.out.println("Value of a.v :" +a.v);
    System.out.println("Value of b.v :" +b.v);
    and write "Clone" method like this: "clone". See that you'll obtain:
    Value of a.v :500
    Value of a.v :100
    good luck!
    m

  • Clone() and equals()-- puzzled!!   x.equals(x.clone())

    hi,
    I have an object x that contains only 1 int variable.I clone the object and check for equality with my original object -- I always get false -- why? Something like:
    boolean flag = x.equals(x.clone())
    Falg is aways false??
    Shoudn't the objects be equal?

    class
    MyClass {
    int x,y
    public MyClass(int X, int Y) { x=X; y=Y; }
    public boolean equals(int X, int Y) { return x==X
    =X && y==Y; }
    public MyClass clone() { return new MyClass(x,y);
    }Well, you'd need to add
    public boolean equals(Object obj) {
        return (obj != null)
                && (obj.getClass() == getClass())
                && (((MyClass)obj).equals(x, y));
    // and you have to override hashCode. Maybe something like...
    public int hashCode() {
        return x ^ y;
    }I'd get rid of the equals(int, int) method though and either compare x & y in[b] equals(Object) or have equals(Object) call equals(MyClass) which would then compare the x & y.
    Also, clone is always supposed to call super.clone()--it should NOT construct a new object with new. It has to catch CloneNotSupportedException, and return Object.

  • Communication between javascript and Objective-c in iOS.

    We wanted to have a communication between javascript and objective c code. We have already tried the below approach.
    To load fake URLs in JS and append a string which will be used as parameter to the Objective-C code and parse that URL in this delegate method:
    -(BOOL)webView(UIWebView *)webView shouldStartLoadWithRequest(NSURLRequest *)request navigationType(UIWebViewNavigationType)navigationType
    Then send the return value by calling the native method stringByEvaluatingJavaScriptFromString again with parameter callID.
    But we wanted to access Objective class object in Javascript code so that we can call it's methods from javascript code using this object.Android supports this behaviour using addJavaScriptInterface method in webview. Is it possible to have the similar approach in IOS? If not what is the best approach possible to acheive this? If we could achieve similar behaviour then we don't need to change the Jacascript code and will be reused. Please suggest the best possible solution.
    Regards,
    Karthik M.

    https://developer.apple.com/library/mac/documentation/AppleApplications/Conceptu al/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html

  • System and Object privileges question

    hello everyone.
    I was really making it a priority to really understand both system and object privileges for users. I have setup a couple of 'sandboxes' at home and have done lots of testing. So far, it has gone very well in helping me understand all the security involved with Oralce (which, IMHO, is flat out awesome!).
    Anyway, a couple of quick questions.
    As a normal user, what view can I use to see what permissions I have in general? what about permissions on other schemas?
    I know I can do a:
    select * from session_privs
    which lists my session privileges.
    What other views (are they views/data dictionary?) that I can use to see what I have? Since this is a normal user, they don't have access to any of the DBA_ views.
    I'll start here for now, but being able to see everything this user has, would be fantastic.
    Cheers,
    TCG

    Sorry. should have elaborated more.
    In SQLPLUS, (logged in while logged into my Linux OS), I am working to try and get sqlplus to display the results of my query so it is easy to read. Right now, it just displays using the first 1/4 or 1/3 of the monitor screen to the left. Make sense? So it does not stretch the results out to utilize the full screen. it is hard to break down and read the results because they are "stacked" on top of each other.
    Would be nice if I could adjust sqlplus so the results are easier to read.
    HTH.
    Jason

  • How to remove file path location listings from photos and objects in Acrobat Pro 9.0 PDF?

    After converting a windows-based Powerpoint 2007 presentation to an Acrobat Pro 9.0 PDF, the file path location of all photos and objects are shown in a dialogue box when the cursor is moved over the image as seen in this screenshot below. How can I stop this from happening and remove this feature on my pdf documents? 

    I saw that referenced on a forum, but it does not seem to address the issue I am having.
    As per Adobe Acrobat X Standard * What’s new, the equivalent to the "Tools > Protection > Remove Hidden Information" utility found in Acrobat X Standard is the same as the "Document > Examine Document" feature in Acrobat Pro 9.0. Those tools seem to cover meta data, book marks, hidden text, and deleted or cropped content, but not the file path listings that appear on images and objects converted from Powerpoint presentations and other MS Office programs.
    I have reviewed the settings used while creating a pdf, and have also tried the “Advanced > Preflight tool”, but could not find anything to apply to the issue at hand.
    Thus, this issue has not been resolved, but seems like it should be an easy fix that anyone who publishes pdf documents would want to use to publish clean, professional documents without anyone seeing the file path location of every object and image shown in the document on their hard drive.

  • Reset Text Wrap and Object Placement defaults?

    Using Pages 5.5.2 (w Yosemite).
    Wondering if there's any way to set a default preference for the Text Wrap and Object Placement parameters in the Format > Arrange tab? 
    For example, more often than not I need to have Text Wrap set to "None", rather than "Automatic".  I was at least hoping that once I'd set a particular object to "None", any new objects I created or which were dragged into that same document would inherit that same Text Wrap setting (in much the same way that any new drop shadow setting becomes the new default when applying the drop shadow effect to subsequent selections). But even THAT doesn't seem to be the case with the Text Wrap & Object Placement options -- much less being able to reset a new global preference.
    Any suggestions (which still involve using Pages 5.5.2) appreciated.
    Thanks,
    John B

    just discovered a related topic: when importing images in Pages, how do I set the default object placement to "stay on page" and "no text wrap"?
    But that thread ends up going in a slightly different direction, since having to create placeholder shapes, and then duplicating (+ individually repositioning) same, for almost every time I dragged an image into a Pages doc would actually be MORE work than the current annoyance of having to reset the Text Wrap setting for most new objects.
    I just want a way to set a global preference for that adjustment -- or at least a preference to have all new objects start off with the same Text Wrap (and Object Placement) settings as the last ones used.
    Possibility?  Or Feature Request?

  • XML attributes and object types

    I want to create an XML Document of the following form
    <family>
    <parent attr1="val1">
    <child attr2="val2" attr3="val3"/>
    </parent>
    </family>
    Using object table and object type (for the child element), I am able to produce the following XML Document (with a "select * from family" query)
    <family> <!-- rowset -->
    <parent> <!-- row -->
    <attr1>val1</attr1>
    <child>
    <attr2>val2</attr2>
    <attr3>val3</attr3>
    </child>
    </parent>
    </family>
    The question is: how am I going to query these data so that the "attr" elements are mapped to attributes (using XSU only, without XSLT)?
    I have already tried the following:
    1. Using
    SELECT attr1 as "@attr1",
    f.child.attr2 "@attr2",
    f.child.attr3 "@attr3"
    FROM family f
    all the attributes are obviously appended to the "parent" element.
    2. Using nested table for "child" and the following query
    SELECT attr1 as "@attr1",
    CURSOR (
    SELECT n.child.attr2 as "@attr2", n.child.attr3 as "@attr3"
    FROM TABLE(f.child n)
    ) AS "child"
    FROM family f
    I am getting the following document
    <family>
    <parent attr1="val1">
    <child>
    <child_ROW attr2="val2" attr3="val3"/>
    </child>
    </parent>
    </family>
    Is there a smart SQL query to produce the desired document? What data types
    is it recommended to use to define my db schema (object types, nested tables...)?
    Thank you in advance
    null

    Finally, I got the desired XML format output from relational tablse using schema based XMLType views.
    Wherein I created Object Types from relational table, generated the schema for the Object type, registered the schema and finally created XMLType Views for populating the XML data from Relational Tables.
    I guess, you all might aware of my problem, where I got struck. Instead of printing the data in XML format I am successful in generating the XML format data Using the Query Select from BLABLA_Type_view* . I am able to print the number of rows, that I require which is in the fallowing format.
    Column Name
    1. SYS.XMLTYPE ----- As a row
    The view I am querying for is printing the data in a string format, where in I got to do the fallowing query
    SELECT SYS.XMLTYPE.getStringVal(OBJECT_VALUE) FROM BLABLA_Type_view. Which ultimately gave me the required data in XML format with tags.
    Thanks for every one who tried to give a try to solve, especially "mdrake"

  • Time_building_block_id and object version number

    Hello,
    could someone help me out with an explanation how the time_building_block_id and object version number to be interpreted?
    Are these independent? What actions create new ID and new ovn?
    My first idea was that one ID can have different instances in the table with different object version numbers. However I found cases belonging to the same parent buildingblock where both the id and ovn are different.
    So based on this only one of the columns could be primary.
    However for the joins both are used typically at the same time, suggesting that the two together constitutes a primary key.
    Are the DETAIL level records belonding to the same DAY level record to be treated as co-existing entries and their measure to be summarized? Or only the latest (bigger ovn?) to be considered, so it is an updated version of the record with the previous ovn?
    thanks!

    The version number in the TC Building blocks is used to identify changes to timecard building blocks. It is not the same as an object version number on a record in a table.
    OTL keeps an audit history of all changes to the timecard, at whatever level they occur. It uses this in retropay processes to identify the 'true' hours to use.
    TC Building blocks have a 'scope', for example there are building blocks at these levels:
    Timecard
    Period / Application
    Day
    Detail
    If you entered 8 hours on a new timecard for Monday 07/09/09 it would create a building block record for that date and call it version 1.
    If you later make a change to that DAY, OTL will create a new record with version 2. Say this one shows 7 hours.
    OTL can then interpret this as -8 + 7 = -1 and make the appropriate adjustment.
    Hope that helps explain it!
    Regards
    Tim

  • Scope and Objectives of making java swing scientific calculator

    I am going to write code for java swing scientific calculator..... can any body help me to write scope and objectives of this project.... please please :-(

    If this is for school work, then defining the scope is part of the problem. The only advice I will give you is that you only need to implement what the assignment specifies. It is probably intentionally vague so you can bite off way too much and not finish -- failure should teach you something too.
    I had just such an assignment in my software engineering class in college -- create a cross compiler from X to Y where X and Y where known instruction sets. That was the entire assignment -- plus the instruction sets for X and Y. My team looked at the allotted time and resources availabe and decided to do a minimal implementation.
    We where the only team to complete the assignment and all recieved A's because we accurately implemented the required solution and were able to evaluate the real problem--resource allotment--accurately.
    Each other team tried to add "extras" that would "guarantee" them an A grade. In actuallity it was just a lot more work than they could do though and it hurt them in the long run--No matter how good the work was to the point they had at the end of the semester, each student in the other teams only recieved a B or less grade in the class due to failure on that project. Resource allocation and planning--only you can do that for your team/project.

Maybe you are looking for

  • GL A/C to be changed for R.M

    Dear All, We have certain raw materials at our plant.  Last week fire took place and many raw materials got damaged.  The damaged raw material are lying in X GL account ( Local inventory GL A/C ) in SAP. We want to transfer the damaged raw material t

  • Button not working on PDF

    I've a button which should add instance of a subform on click event using following script - xfa.host.messageBox("adding instance", "Warning", 3); Detail.Blank_Page.ItemSet.instanceManager.addInstance(1); Detail.Blank_Page.execInitialize(); When I cl

  • Call a PL/SQL Package

    Hi All, I'm using ADF BC, JDev 11G. I need to call a stored package to do the validations for the data entered in the page design. I would like to know how to call the package from AppmoduleImpl.java Any example for reference would be helpful. Thanks

  • Ethernet Card Stopped Working (BCM5785M)

    My ethernet card stopped functioning about a week ago, at the time I thought my cable had died and did not think to much of it. Then I checked the cable in my desktop computer and it worked fine and was able to connect to my router as well as the int

  • Arial font missing from Mountain Lion

    Arial font doesn't appear in Mountain Lion, but all my spreadsheets use it.  As a result, when I open any spreadsheet, it appears blank until I change the font.  Is there any way I can fix this?  Thanks