1

first time commenter here. I'm trying to add char arrays to a Binary Tree in java. The problem is that when I try to make the char array into a node (prior to adding the node to the tree), the node is not a char array but a reference. Here is my making-things-a-node class:

public class TreeNode {

char[] data;
TreeNode left, right, parent;
public TreeNode(char[] data) {
    this.data = data;
    left = right = parent = null;
}
}

and here is the line I'm using to pass the char array to the node class:

TreeNode theNode = new TreeNode(dictionary);

where dictionary is a char array. And when I print theNode I get something like this: ([C@58623a98). I think the problem might be with the this.data but I'm not sure. Can anyone help me?

Update: when I print dictionary I get the char array I started with.

jani
  • 107
  • 1
  • 4
  • 13

2 Answers2

2

What you describe is normal behaviour. The outcome of printing an object is determined by its .toString() method. If no .toString() method is declared, the default .toString() method inherited from Object class is used, which gives the output you received.

If you want the array to look nice when printed, you can define your own .toString() method, or use an utility method of Arrays.toString(yourArray).

Warlord
  • 2,754
  • 14
  • 21
0

The observation is correct that each node has access to the same character array1; if you want a copy of any object, make a copy of an object.

Either of the following are sufficient to make a copy of a primitive array, although clone has a bad reputation in general.

this.data = Arrays.copyOf(data, data.length);
this.data = data.clone();

Alternatively, you could make it the callers responsibility to pass in different objects.

// i.e. when omitting the above
new TreeNode(dictionary.clone());

More complex objects/object-graphs will require different handling. My recommendation is to simply try and reduce mutable objects which eliminates the need for making the appropriate copies.


1 That is, objects are not copied/cloned/duplicated when they are passed in Java; rather, the value of the reference to the object is passed, and hence the same object is referred to.

Community
  • 1
  • 1
user2864740
  • 54,112
  • 10
  • 112
  • 187