Deep copy of String
As String is called by reference, how can I perform deep copy?
Anything similar to System.arraycopy for String?
That's funny, this works for me:
String k = "kkkkkkkk";
String m = k;
Now, when I change 'k' (f.i. k = k.substring(0, 2); )
'm' does not change.
So that's a deep copy!
;JOOP!No - it's not a deep copy. Your statement k = k.substring(0, 2) does not change the string that was referenced by k previously, but changes the k variable itself so that it references a new string.
It's really important to get a handle on the difference between objects
on the one hand, and references to them on the other. Without that understanding you have little hope of writing correct and efficient Java programs.
Sylvia.
Similar Messages
-
I wrote a stack implementation using a LinkedList, I have null constructor to create the first stack and it works fine but now i have to create a copy for a second stack using the element of the first constructor
this my code
import java.util.LinkedList;
public class Stack<T>{
private LinkedList<T> stack;
public Stack(){
stack = new LinkedList<T>();
public Stack(Stack<T> s) {// the problem is here it compile but when i run
// the program the second stack raised an exception because is empty
// i want to create a deep copy with the elements of the first stack
stack = new LinkedList<T>();
public boolean isEmpty(){
return stack.isEmpty();
public void push(T item){
/*method to add object information
*pre the object is not full
* pos: the object is inserted
stack.addFirst(item);
public T top() throws EmptyStackException{
if (!stack.isEmpty()){
return stack.getFirst();
else{
throw new EmptyStackException("StackException on top " + " Stack empty");
public T pop() throws EmptyStackException{
/*method to remove an element of the stack
*pre the object is not empty
* pos: the object is remove
* response throws an exception
if (!stack.isEmpty()){
return stack.removeFirst();
else{
throw new EmptyStackException("StackException on top" + "stack empty");
public int numElements(){
return stack.size();
public void clear(){
stack.clear();
public class EmptyStackException extends Exception{
public EmptyStackException( String message){
super(message);
}wel well... are you doing this on a mobile phone???
neways to get to ur question u can use the clone() method to generate a clone of your object which is the same as a deep copy for eg:
public class CloneTest{
CloneTest test1 = new CloneTest();
CloneTest test2;
CloneTest(){
//Some initialization code;
CloneTest(CloneTest temp){
test2 = test1.clone();
}clone is a method of the object class. -
Clarification regarding deep cloning/deep copy
Hi,
While performing deep copy of an object should all the subobject that the parent object constitute also constitute the clone method.
For Eg:
I have a class called Document and a class called Field. Document constitutes of List<Field> fields. Field class has a String fieldName as its member variable.
I need to perform a deep copy of Document object. Should Field class also implement the clone method or can I create field objects in the documents clone method and fill these fields with values from the existing field list to form a new Document with these new fields.
Or do I call clone() method on each field to get a new field object and
add it to the new Document object that I am creating in the clone() method .
//First approach
public Document clone(){
Document doc = new Document();
List<Field> fields = doc.getFields()
Field newField = null;
for(Field f: fields){
newField = new Field();
newField.setName(f.getName());
doc.addField(newField);
return doc;
//Second Approach
public Document clone(){
Document doc = new Document();
List<Field> fields = doc.getFields()
Field newField = null;
for(Field f: fields){
newField = f.clone()
doc.addField(newField);
return doc;
}Please let me know which is a better approach and the standard coding
practise.
Thanksthe second method is better, because it lets you the possibility to create a subclass of Field with a specific clone method, integrate some instances in a Document object; without changing the Document.clone method.
-
ObjectUtil doesnt deep copy correctly
I am using an ObjectProxy for a complex object containing
arrays of objects. I bind a datagrid to the array and . notation to
fields. This all works fine, datagrid behaiving properly, inserts
and deletes working properly.
I want to have an undo function that will put the objectproxy
object back to its original state. So when i open the screen with
the datagrid I do a ObjectUtil.copy() and use this latter if the
user wants to revert changes. The problem is that the copy doesn't
do a deep copy. In the Object is an ArrayCollection of userdefined
objects. These objects instead of being copied as their type are
being copied as plain objects.
The serialize meathod the copy uses doesn't retain the types
of user defined objects.
Will I have to create clone or copy methods for every object
type I have?
If so do I just need to make them ezxternalizable? How will
the objectutil copy pick up these methods?
Thanks,
JeffUnfortunatlly you will need to implement it for every class
that has complex objects, as it does not know how to deal with
them. Your classes need to extend EventDispatcher and/or implement
IExternalizable.
Then create methods writeExternal and readExternal for every
local variables you need to retain. eg..
public function writeExternal(output:IDataOutput):void {
output.writeUTF(msgString);
output.writeObject(anyObject);
output.writeInt(id);
public function readExternal(input:IDataInput):void {
msgString = input.readUTF()as String;
anyObject = input.readObject()as Array;
id = input.readInt() as int;
} -
What is the best practice for sending doing a deep copy between two View Controllers in an iPhone app. I've designed an app that sends over arrays of arrays and the deeper items aren't coming over as easily as I thought. Do you explicitly copy? Just alloc placeholders and set them equal? Links to any samples would be greatly appreciated.
Is it a best practice to avoid that kind of data passing - as being overly complex?
Background:
I'm building an iPhone application where I need to send a complex object from one view controller to another - This complex object is an array of arrays of objects.
I can't just copy a reference to the complex object over to a variable on the receiving view controller, as none of the nested array contents come over.
So I think I need to do a deep copy - but need advice on best practices for that. The array of arrays contain objects, so ideally, Id just be able to :
Thanks for any advice!There are many ways of solving this.
One way is to centralize the information:
You create a singleton class that is the datasource for both view, so you don't need to pass in anything. If you can't do that because the datasources are generally different except for this specific array of arrays, then make the singleton class be the source of that array and nothing else. -
Hi all,
I have a question I can't find any documentation about, not on google, not here on the forums. We are developping a EJB J2EE application (with glassfish) with flex as the view. We are using BlazeDS to interchange objects back and forth between flex and java.
The problem we are having is we have to do a deep copy of an object tree, but blaze by default copies shallow.
The setup is like this:
We generated the actionscript classes that represent the java classes on the client side with a code generator named Gas3 (the only one out there, no?). This generator created classes with RemoteClass and Bindable annotations already in place. Gas3 also implemented the IExternalizable interface but we threw that out because it gave us problems in java. We have our EJB services configured in the remoting-config.xml file and everything works except for deep copy so I don't think there is anything missing, no?
Is somebody aware of a way we can achieve a deep copy? I imagine there would be an xml tag or attribute that would allow for this ...
Any help would be greatly appreciated!
Thank you,
Bruno Windels
3SOr is it creating a deep copy of each element in the Array and placing them into a new array object?
-
How to deep copy a component configuration?
Hi Experts,
I want to deep copy a component configuration named EHHSS_RAS_OIF.
But following was the error shown.
Can you please help/guide to do the same.
Thanks in advance.
Sanket.Hi Sanket,
I think you might be copying the config in Unit test client but not in Development client.
Thanks
KH -
Shallow copying and Deep copying ???
hi,
what is meant by shallow copying and deep copying in context to clone() method found in Object class?
thanks,
swapnajaswapnaja wrote:
Shallow copying: only cloneable object is copied but any object references within that object would not be copied but would rather be shared.
Deep copying: cloneable object along with any object references contained within that object will also be copied.
Am i right?Yep; when you want to make a deep copy you have to watch out for circular references, i.e. if you have made a copy of an object already you shouldn't make another one during the deep copying process; (see how the ObjectOutputStream does things).
kind regards,
Jos -
hi,
any body tell me what is the difference between shadow copy and deep copy of a object.would you tell me any prectical example of this. i
mean when i should use shallow copy and when i should
use deep copy of object.I'm hoping someone else will step in here, because in my OO thinking, there's seldom a need for copying an object at all.
One practical example, though: Say you're copying a list of objects. After the copy, you want to alter the objects in the copied list, but you don't want the objects in the original list altered. In this case, you need a deep copy. Had you only done a shallow copy, both lists would have referred to the same objects, and therefore, any change in an object would be visible through both lists.
clone() method makes shallow copy or deep copy.You'd have to consult the doc for the class you are cloning. For example, the doc for LinkedList.clone() says "Returns a shallow copy of this LinkedList." -
How does deep copy apply to arrays?
I have a service object that has a method that returns an array of
objects. The return type for the method is defined with the copy option.
I found documentation that states that the copy option creates a deep
copy of the return variable on the partition that called the method.
My question is: If the return type for the method is an array of
objects, will the copy option create copies of all objects/elements in
the array?
We wish to eliminate any object references to the service object's
partition. Any insight would be greatly appreciated.
Thanks in advance,
Van Vuong
Phone: 972.985.5289
Pager: 972.320.2232
VoiceNow Pager: 972.330.0822
E-mail: [email protected]
PAGE NETCopy option always copies deep. Remember, also if you pass the array
accross partitions, whether you specify copy or not, it is going to copy
and copy deep.
In an array, I am not sure if have the problem, because unless the array
in-turn holds a huge tree, the array object may be wide, but not deep.
Some thing to think about??
Venkat -
Dear all,
I am struggle with deep copying a priorityQueue. Anybody has a clue about his. It seems onyl swallow copy is allowed.
Cheers,
KeSee
http://java.sun.com/docs/books/tutorial/java/IandI/objectclass.html
http://www.google.com/search?num=100&hl=en&c2coff=1&q=java+deep+shallow+copy&btnG=Search -
hi guys, i have an object which extends defaultmutabletreenode, basically it is a leaf on a tree and these leafes (not leaves then i guess but you know what i mean) have leaves themselves, as shown below, every node has an arraylist and these nodes also contain arraylists. i want to clone this object to see if it is quicker than re-creating it all of the time but i am a little hesitent as i am worried about getting a deep clone to work and unfortunately i couldnt find one that someone has already written.
am i right in thinking that you cant simply clone mychildren, you then have to go to every chidl and clone its children also??
below is the top of the class so you cans ee what it looks like...could anyone post a loop that would clone the tree or if it is a lot of trouble just a description of what i need to do would be great!
public class Node extends DefaultMutableTreeNode
private RootNode myRootNode;
private ArrayList<Node> myChildren;
thanks in advance to all who reply
Danny =)Yeah in that article I'm pretty sure he talks about putting it through a PipedInputStream to a PipedOutputStream (or vice versa?). That should be considerably faster than writing to a disk.
I think you're going to be better off writing your own deep copy method though, it's a pretty simple structure, not worth the extra overhead...
p.s. Are you positive that you need to clone everything all the time? -
Problem in copy a string to a message parameter
Hi all,
I have a problem in copy a static string into a message as its parameter.
I use the default function in creating the copy rules...
<copy xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<from expression="string(WS1-PSC4-KUY2)">
</from>
<to variable="geo_in" part="parameters" query="/ns0:GetLocationByIP/ns0:LicenseKey"/>
</copy>
as the string is a liscence key to use this web service.
However, the string is not copied to anywhere of the outgoing message.
If I use the default type 'literal' and copy to the variable parameter,
it looks like this...
<copy xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<from>
WS1-PSC4-KUY2
</from>
<to variable="geo_in" part="parameters" query="/ns0:GetLocationByIP/ns0:LicenseKey"/>
</copy>
it gives me an error...
[bpelc] BPEL source validation failed, the errors are:
[bpelc]
[bpelc] [Error]: Element 'from' must have no character [children], because the types content type is element-only.
[bpelc] [Description]: in line 43 of "C:\eclipse\workspace\ip_locate\ip_locate.bpel", Element 'from' must have no character [children], because the types content type is element-only..
[bpelc] [Potential fix]: .
[bpelc] .
Could anybody give me a hint on what's going wrong?This is my actual code
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class TestingDate {
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
String dateFormat="EEEE, MMM d h:mm a";
Date test=new Date(2007,0,19, 19, 31);
System.out.println(" original date is "+test);
String stringResult=DateToString(test,dateFormat);
System.out.println("Date to string is "+stringResult);
Date dateResult=stringToDate(stringResult,dateFormat);
System.out.println(" String to date is "+dateResult);
String stringResult2=DateToString(dateResult,dateFormat);
System.out.println(" Date to string is "+stringResult2);
public static String DateToString(Date test, String dateFormat) {
String result = null;
try {
DateFormat myDateFormat = new SimpleDateFormat(dateFormat);
result = myDateFormat.format(test);
//System.out.println(" reslut date is "+result);
} catch (Exception e) {
System.out.println(" Exception is "+e);
return result;
public static Date stringToDate(String strDate,String dateFormat1){
Date result1=null;
try {
DateFormat myDateFormat = new SimpleDateFormat(dateFormat1);
result1=myDateFormat.parse(strDate);
catch(Exception e){
System.out.println(" exception is "+e);
return result1;
}I am facing problem in getting the actual date. Please suggest the solution. -
Copy a String (easy right?)
Ok, I am running into a problem and I must be missing something simple. I am trying to 'copy' the text from a UITextView into a string to make a "backup" of the data. Then I manipulate the data in the textview and if the user doesnt like it they can revert back to the original data. The problem is that when I try and set the data of the textview back to the copy I made, the copy is now the same changed data that the textview has. How can I make a true copy of the data?
I have tried many things, here is one example:
originalText = [NSString stringWithFormat:@"%@", [textView text]];
[originalText retain];
processing of the textView text
User wants to revert back to original text
textView.text = [NSString stringWithFormat:@"%@", originalText];
The problem is that originalText has been changed and holds the manipulated data. Any ideas??
ThanksSounds like your accessors may not be making a true copy. The only way that I can see your problem happening as described is that originalText and textView.text are pointing to the same string.
-
How to copy one string to another string?
suppose you have 2 local strings strA, strB. can you show me an expression that copy the content of strA to strB?
ThanksLocals.strB = Locals.strA
Maybe you are looking for
-
I try to send a message to my friends and then it crashes
By mistake i deleted ichat, i installed it again from my install disk and after that im having the problem that i cant send any messages to my friends and it also crashes.Heres the error: Process: iChat [678] Path: /Applications/iChat.app/Contents/Ma
-
Accept SMTP relays only from these hosts...
Do we need to enable at all this thing in Server Admin? Since we require from everyone to use authentication in order to send mail (even inside the company's network). I noticed that when enabled and set to our inside network, in main.cf the mynetwor
-
Hi all, I am getting an error in batch input(for transaction FB01) ,while running RFBIBL01, errror is "Field COBL-KOSTL. does not exist in the screen SAPLKACB 0002". Could anyone help me out . Thanks, Bobs
-
How to make bookmarked webpages available offline? Like in Internet Explorer?
I wanted to make the webpages I bookmarked available offline. I could do this in the Internet Explorer by simply tweaking some of the bookmarks options. But I'm not able to do it in Firefox. Could please anyone help me? Thanks in advance.
-
E7 - screen unresponsive when charging
The touchscreen on my E7 becomes unresponsive while charging. Essentially it seems to be losing it's accuracy. It stilll works somewhat but you have to tap all over the screen to get a response, and then it's not the one you want. I noticed the same