Creating a deep copy method, Java - java

I want to make a deep copy method. I seeked help here the other day with this issue, but that was for a copy constructor. Now I need a regular method. I have the code created (nonworking), but I'm just not understanding it completely.
public GhostList deepCopy(){
int length=this.getLength();
GhostList jadeed=new GhostList();
Ghost[] data = new Ghost[length];
for (int i=0;i<this.getLength();i++){
data[i] = new Ghost();
data[i].setX(this.ghosts[i].getX());
data[i].setY(this.ghosts[i].getY());
data[i].setColor(this.ghosts[i].getColor());
data[i].setDirection(this.ghosts[i].getDirection());
}
return jadeed;
}
Now when I create a new GhostList named jadeed, and then under that I create a new data array of ghosts, does it know that data belongs to the jadeed GhostList? I dont see how the two can be associated, even though they should be.
Also, I'm not getting the lengths to match up for the copy and this.object. What is my problem?

You created a new GhostList and a new Ghost array.
You fill in the Ghost array and return the GhostList but the returned GhostList has nothing to do with the Ghost array.
You should add all the new ghosts to the GhostList

First, you mentioned a copy constructor. If you already have that working, then all you need to do in your deepCopy method is:
return new GhostList(this);
Let's forget that for now and get back to the code you posted. You are creating an array named data but you never used it anywhere. Aren't you supposed to assign this array to jadeed? Something like:
jadeed.ghosts = data;
And finally, instead of calling the method deepCopy, it would be better to call it clone and implement the Cloneable interface. Doing this allows everyone to know how to get a copy of your object using a standard interface.

Your GhostList class will have as its data member a reference to the array of Ghost. You've not shown us the class definition, so lets say that member is named foo. Now all you need to do is make the foo reference of the newly created jadeed object refer to the array of Ghost which you've created and populated. You can do it as:
jadeed.foo = data;
before you return jadeed.

If GhostList and everything it's composed of is Serializable, you can serialize the GhostList instance into a byte array and re-read it. It's a few lines of code, unless you use `Jakarta Commons Lang - one line of code:
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/SerializationUtils.html#clone%28java.io.Serializable%29

Related

Object Array to TextArea

I have an array of objects and i want to print them out to a TextArea in a JavaFX program. Im not sure how to go about doing that. Everything that im try doesnt work.
for(int i = 0; i < set.getEngCourse().length; i++){
txt.append(set.getEngCourse()[i]);
if(i != set.getEngCourse().length -1){
txt.append("\n");
}
taken = new TextArea(txt.toString());
The object im trying to get onto the TextArea is a couple of course objects.
There are some assumptions to be made, since not all of the code is posted. We will assume that set.getEngCourse() properly returns an array of some Object, and that set cannot be null, and that .getEngCourse() returns at a minimum an empty array and not a null if there are no courses (if either of these assumptions can be violated, add appropriate null checks). It would be best if the returned array were of some specific type (e.g., EngCourse), but the OP code does not make clear what is in the array.
I would approach the solution in a manner similar to the following:
StringBuilder txt = new StringBuilder(); // get something to collect the output
for (Object obj : set.getEngCourse) { // If possible, change Object to the specific type
// add a line break if we have already added something,
if (txt.length() > 0) {
txt.append("\n");
}
txt.append(String.valueOf(obj)); // will handle null objects
}
taken = new TextArea(txt.toString()); // assumes taken is declared elsewhere
If there is a known object type, it would be better to:
Override the .toString() on the object type
Use the specific object type in the iteration
for (EngCourse ec : set.getEngCourse()) { //use specific type
...
txt.append(ec.toString()); //technically, the .toString() is not needed
}
Also, if the .getEngCourse() returns multiple objects, I would recommend changing the name to .getEngCourses() to make clear that it is returning N courses, and not just a single course.
If a TextArea is not strictly required, I would also consider using a JList or something similar. Basically, dumping everything in to a TextArea simply gives output, without much ability to do anything else with it (such as select a particular course for future operations). Consider, e.g., this SO answer Java JList model. In essence model the domain using appropriate classes, and then use a model/view/controller approach to display the domain classes rather than thinking of the domain as essentially String objects.
Is your txt object a string? If so then why are you putting a txt.toString in the last line of your snippet?
You can use setText function to display the contents in your text area.
Post the error or problem more specifically and extend your code snippet for us to know the scope of for loop.

Java: Getting object associated with enum

I have an ArrayList full of custom objects. I need to save this ArrayList to a Bundle and then retrieve it later.
Having failed with both Serializable and Parcelable, I'm now simply trying to somehow save the objects that are associated with the indexes in the ArrayList, then checking these when restoring the Bundle and adding the objects back in.
What I have is something like this:
When saving the Bundle:
//Create temporary array of the same length as my ArrayList
String [] tempStringArray = new String[myList.size()];
//Convert the enum to a string and save it in the temporary array
for (int i = 0; i<myList.size();i++){
tempStringArray [i] = myList.get(i).getType(); //returns the enum in string form
}
//Write this to the Bundle
bundle.putStringArray("List", tempStringArray);
So I now have an array of strings representing the enum types of the objects that were originally in the ArrayList.
So, when restoring the Bundle, what I'm trying is something like this:
//Temporary string array
String[] tempStringArray = savedState.getStringArray("List");
//Temporary enum array
ObjectType[] tempEnumArray = new ObjectType[tempStringArray.length];
for (int i = 0; i<tempStringArray.length;i++){
tempEnumArray[i]=ObjectType.valueOf(tempEnemies[i]);
}
So, now I have the enum type of each item that was originally in the ArrayList.
What I'm now trying to do now, is something like (would go inside the for loop above):
myList.add(tempEnumArray[i].ObjectTypeThisEnumRefersTo());
Obviously the "ObjectTypeThisEnumRefersTo()" method above doesn't exist but this is ultimately, what I'm trying to find out. Is this possible or perhaps there is some other way of doing this?
To get an enum value of the enum type Enemy from a string, use
Enemy.valueOf(String).
Enemy.valueOf("SPIDER") would return Enemy.SPIDER, provided your enum looks like
enum Enemy { SPIDER, BEE};
EDIT: It turns out Zippy also had a fixed set of Enemy objects, each mapped to each value of EnemyType, and needed a way to find an Enemy from a given EnemyType. My suggestion is to create a
HashMap<EnemyType, Enemy>
and put all the objects in there upon creation, then at deserialization convert strings to enum values and enum values to Enemy objects using the hashmap.
It later occurred to me though that depending on how much logic you have in Enemy, you might want to consider scrapping either Enemy or EnemyType and combine them into one parameterized enum, similar to the example with Planet over here:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
That would spare you from having to go two steps from a string to your final object and simplify things a bit as you wouldn't need any hashmap after all.

java naming an object from an aspect of another object

I am trying to create an object named after an aspect of another object. I assumed that I would need to change count.counts value into a string in order for this to work but I cannot work out how to reference this in creating the new object.
This is the code i have;
String no=Integer.toString(count.count);
BattleCruiser =new BattleCruiser();
EList.add(battle);
count.count++;
An object does not have a name. We give names to variables so that we know what they point to, what they represent.
Dynamically name a variable does not seem very useful, since you need to reference it afterwards. If the reference is dynamic too, then why not use a data structure instead? For instance:
If you're trying to give numbers to your variables, for instance ship0, ship1... then you can use an array ships instead, and access ships[0], ships[1].
If you want more general names that reference objects, you can use a Map<String,Object> instead.

Different objects in array

Good time of the day to anybody reading,
I would like to ask if the following situation is possible to do in Java:
What do I want to do - create a 2D array which can have different objects in it (i.e. in [0][2] I would like to have PreRoom object, in [0][3] - Room object) and would like these object to be accessible (obviously).
How am I doing this?
1) Declare 2D array of Object type:
Object[][] map = new Object[151][151];
2) Create an object:
map[0][2] = new PreRoom(r, true);
3) But after this I'm unable to use any method of PreRoom/get any its property, i.e. unable to do:
map[0][2].x;
//or
map[0][2].getR;
Am I doing this wrong? Or it's impossible to do and therefore the only solution is to create a unified object for current 2?
Thanks in advance.
EDIT: solution found, thanks for the replies.
You declare Object[][] map = new Object[151][151]; So anything you store in it will be an Object (Obviously), so how does it know that your Object in map[0][2] is of PreRoom? You will need to cast it as such so you can use any methods of PreRoom
((PreRoom)map[0][2]).methodName();
Be careful in future if you are storing numerous types in your map. You may find instanceof useful if you ever need to iterate through your map not knowing which values are of what.
For example;
if(map[x][y] instanceof PreRoom) {
//map[x][y] is an instance of your PreRoom class
PreRoom preRoomObj = (PreRoom) map[x][y];
}
You can define an interface or abstract class that will be implemented/inheritedd by both PreRoom and Room class.
Then you array could be something like
<InterfaceName/AbstractClassName>[] = new <InterfaceName/AbstractClassName>[151][151];
You interface or base class should declare the common methods and variable.
Here you need to explicitly type cast to call the methods on that object
((PreRoom)map[0][2]).x

Android - Accessing Array in multiple activities

Just a real quick question. I've defined an array in one activity and I'm trying to access it in another one. I was planing to extend it as so:
public class MyChallenges extends Main {
But I need to extend 'ListActivity' to get my code to work, as I am using a custom listview, so I can't extend two activities. As shown:
public class MyChallenges extends ListActivity {
Is there any other way, apart from extending the main activity? This is the array I'm trying to access for read and write:
public String[][] arr = new String[2][6];
So, in short, how can I access the array 'arr' from another class? Thanks guys!
Make a class that contains the array, and reference that class from your activities. For example:
public class ArrayOfStuff
{
public static String[][] arr = new String[2][6];
}
Then, to modify the array, use something like ArrayOfStuff.arr[1][1] = "foo";
Happy coding!
The element of a resources file can only be used for single dimension arrays. In other words, everything between and is considered to be a single string.
If you want to store data in the way you describe (effectively pseudo-XML), you'll need to get the items as a single String[] using getStringArray(...) and parse the and elements yourself.
Personally I'd possibly go with a de-limited format such as...
Bahrain,12345
...then just use split(...).
Alternatively, define each as a JSONObject such as... and treat this array as JSON object and use JSON method for get value for element...
{name:Bahrain,codes:12345}
->simply create string array at res/values/strings.xml:
->after u can access this string array in whole application...

Categories

Resources