Temp store an object in java - java

Is it possible to temporarily store an object?
What I intend doing is to temporarily store an object, remove the original then put the temp object elsewhere?
So this gives the impression I'm "moving" the object effectively.
Many thanks,

Player tempPlayer = new Player();
tempPlayer.setValueA() = originalPlayer.getValueA();
// copy all values this way
team.remove(originalPlayer);
// more code
team2.add(tempPlayer);
Does this answer look ok?

If I understand you correctly, you have two lists:
ArrayList<Player> team1, team2;
And you want to move a player from team1 to team2.
It appears you want to add a copy, not the original, to the new team. Changed slightly:
There are two ways to do that, the short way and the clear way. Either way, you'll need the index of the player. You probably want the clear way:
Player oldPlayer = team1.remove(playerIndex);
Player newPlayer = oldPlayer.clone();
team2.add(newPlayer);
For reference, the faster way is:
team2.add(team1.remove(playerIndex).clone());
Although this does require you to implement the Cloneable interface.

This assumes the player you intend to move from team A to team B is the k-th player in team A (counting from 0, i.e. for the first player k=0, etc):
ArrayList<Player> teamA = ... // contains player p
ArrayList<Player> teamB = ... // does not contain player p
Player p = teamA.get(k);
teamB.add(p);
teamA.remove(p); // Note: you can also use index
There may be other methods of getting access to the player you intend to move depending on the context. See ArrayList for more available methods.

I know I'm a bit late, but for others that find themselves here:
The most practical thing to use in this case are Stacks or Deques.
These allow you to add objects to a stack and then pop them which removes them.
Stacks do things pretty much the same way Deques do, but Deques are actually a bit more flexible and preferred over Stacks in coding.

Related

How can I use a Linked list with my Handler class in Java?

I am making a simple game which has an array of objects called beats which move along the screen towards a stationary player like a basic rhythm game, and I have decided that using a linked list is the best way to track the nearest beat to the player
Currently I am trying to add to the linked list, and have this as a starting point:
public static LinkedList<Beat> beatLinkedList = new LinkedList<Beat>();
The linked list is public and static as it needs to be accessed in a different class.
int startingPoint = 800;
//For loop 51 times
for(int i=0;i<=50;i++){
//modifier to start position to create differing gaps between beats
int startModifier = random.nextInt(50);
beatLinkedList.add(new Beat(startingPoint,300,ID.Beat));
System.out.println(beatLinkedList.get(0));
//redefines the starting point for each beat
startingPoint = startingPoint+50+startModifier;
}
}
When I want to render the objects however I need to use the handler class, to add the objects to a linked list of gameobjects which has the render method called on them which I would like to keep the same ideally meaning I need to use the handler classes addObject method:
public void addObject(GameObject object){
//linked list built in method to add an object
this.object.add(object);
}
For using an array this solution worked
But something similar for the linked list does not
handler.addObject(beatLinkedList.add(new Beat(startingPoint,300,ID.Beat)));
I should also add that when I get the element at position 0 it outputs all 51 objects which is also a problem.
With trying to use the handler like this I am given an exception saying "addoObject in Handler cannot be applied to boolean"on line 50:
handler.addObject(beatLinkedList.add(new Beat(startingPoint,300,ID.Beat)));
I'm not sure about this but it seems that I need to give a pointer to a location when using the add method and so I tried this:
beatLinkedList.addLast(new Beat(startingPoint,300,ID.Beat));
And this method still has the problem of adding all 51 objects to the same point in the list, which I imagine is something to do with being in a for loop still.
handler.addObject(beatLinkedList.addLast(new Beat(startingPoint,300,ID.Beat)));
Trying to utilise this with my handler class results in a different error from before saying that the 'void' type is not allowed as a parameter. I'm really not sure where to go from here.
beatLinkedList.addLast(new Beat(startingPoint,300,ID.Beat));
handler.addObject(beatLinkedList.getLast());
Solved thanks to Abra's comment, I decided to add the object to 2 seperate linked lists, one of just the beats, and one containing all the game objects, which allows them to be rendered properly, while also allowing beats to be identified and removed when necessary.

How would I define an infinite number of variables? *Java*

I am creating a game, and it requires an infinite number of Rectangles.
For example, let's say I name the variables car:
public Rectangle car1;
public Rectangle car2;
public Rectangle car3;
and so on,
Would there be an easier way? Like:
public int carNumber;
public Rectange car + carNumber;//if carNumber was one, it would be called car1
Also, I will need to test if the rectangles contain others. <-- I know how to do this.
You can't and shouldn't try to declare an infinite number of anything -- just doesn't make sense. Instead use a collection such as an ArrayList that can hold a variable number of object references. e.g.,
private List<Rectangle> carList = new ArrayList<>();
This won't work:
public Rectange car + carNumber;//if carNumber was one, it would be called car1
because variable names don't work that way, they can't be created by concatenating Strings. But don't worry about this, because the ArrayList will take care of this. The third item in the list would be obtainable easy enough: carList.get(2).
To see if any Rectangles in the list contain another Rectangle use a for loop and iterate through the collection:
for (Rectangle rect : carList) {
if (rect.contains(testRectangle) {
// this item contains the test Rectangle
}
}
You would use an ArrayList to do this
Arrays are static memory allocation. You always need to state the size of the array upon array creation, thus not possible to have an "infinite" array. What you are looking for is called dynamic memory allocation.
One example of using dynamic memory is ArrayList.
ArrayList allows you to expand it when elements are added and shrink it when elements are removed. You can expand the size of an ArrayList so called "infinitely" by keep on adding elements into it. However the limit for number of elements you can add to it depends on how much memory your system has.
Basically, dynamic memory allocation is what you are looking for. You may also consider using Vector.
Sorry You can't do it in JAVA. You can't create a variable name dynamically.
I am creating a game, and it requires an infinite number of Rectangles.
You will get OutOfMemory in case of infinite number of Rectangles. Please think about it again.
You can use a static array if the number of rectangles is already known.
Rectangle[] rec = new Rectangle[size];
//get the first Rectangle
Rectangle first = rec[0];
// get the total no of Rectangles
int length = rec.length();
in general code like:
car1 = "blue";
car2 = "red";
car3 = "green";
is 99% of the time better expressed as an array
cars = ["blue", "red", "green"]
In Java arrays are of fixed length when you initialize them, so you could just make a big one or you could use an ArrayList as an above commenter mentioned which is a list-structure that allows for one by one additions.

Will adding an ArrayList to another then clearing it afterwards reset the new?

I know the title is misleading, but it's the best I could do. Here's my situation
public static ArrayList<Monster> wave = new ArrayList<Monster>();
public static ArrayList<ArrayList<Monster>> waves = new ArrayList<ArrayList<Monster>>();
...
for(int i = 0; i < 2; i++){
while(condition){
//Add elements to the wave ArrayList
}
waves.add(wave); //IMPORTANT
wave.clear(); //LINES
}
So here's my question; when I add wave to the waves ArrayList is it going to create a copy of it in memory, or will it actually pass the exact wave in memory to the new ArrayList? The reason I'm asking is, that I'm afraid, that clearing the wave ArrayList after adding it might result in loss of data in the waves ArrayList
Pass wave to a new ArrayList constructor in order to deep-copy it:
waves.add(new ArrayList<Monster>(wave));
wave.clear();
If Monster class contains non-primitive fields, you might have to deep-copy those too.
It will pass the original list. It will not create a copy.
If you want to create a copy, you will have to do it yourself, e.g.
waves.add(new ArrayList<Monster>(wave));
Pay attention that the values of the list (monsters) will not be copied.
you need to understand what a reference is when you add wawe to waves you are adding the reference of it. When you clear the wave, wave in waves will be cleared as well.
When you pass Object in Java you always pass references.
So the Wave Array that you've added to Waves is the exact same array you have in Wave.
When you clear() Wave, you've cleared the object in Waves as well, because they are the same object.

Objects lost in array

I am making a RPG-style program, but I have trouble to get my array of treasure objects to work. I want to save all treasures I find in the array, to be printed out later. Here is the code for the treasure class:
private static int x = 0;
Treasure treasureArray[] = new Treasure[20];
public void collectedTreasures(Treasure t){
treasureArray[x] = t;
x++;
}
And in the main program:
GoldTreasure t = new Coin();
hero1.setPoints(t.getCoin());
t.collectedTreasures(t);
The creation of the treasure object is within a switch within a infinite loop.
When i print out the array, with method
public void printTreasures(){
for (int y=0 ; y<x ; y++){
System.out.print(treasureArray[y] + ", ");
I only get "null" for as many treasures there should be in the array. If i print out the array after t.collectedTreasures(t), I see that only the last treasure is there, and the indexes before that object is null. What have I done wrong?
Yes I'm a newbie. Be nice.
This code is quite suspicious:
GoldTreasure t = new Coin();
hero1.setPoints(t.getCoin());
t.collectedTreasures(t);
It means you are:
creating a new treasure t;
calling collectedTreasures on that very instance.
You should assign the treasure array to the hero, not to the treasure itself.
Also note that x should not be a static variable because it will get shared among all instances; clearly not your intention, since the treasure array is per-instance.
The problem is that you collect the treasure in itself because you call the collect function - that belongs to a treasure - to collect itself.
Later on, when you call printTreasures in what object does it run? Do you create a new instance of treasure and ask for it to print what it has collected? If such, the results are according to the code and there is no issue with it, but the logic is faulty.
What you should do: the hero is the one collecting the treasures, therefore move the definition of the array of treasures, the counter and the 2 functions - collectedTreasures and printTreasures - in the hero class. Further more, make X not static, as its value will be shared among heroes. Maybe, even more ellegant, create an additional class to handle the treasures and compose you hero using different classes.
And may I suggest a renamig for the collectedTreasures(Treasure t) function to collectTreasure(Treasure t).
We would need to see your full code to give you a detailed answer, but I suspect what you are doing is creating lots of Treasure subclasses and calling collectedTreasure on each one. This is going to increment your global x counter each time, whereas each individual treasureArray only has one entry in it.
You can move the collectedTreasure method to the class corresponding to your hero1 object, at the same time, get rid of the static (global) x variable and replace your array of Treasure objects with a List implementation (e.g. ArrayList), they all keep track of their own sizes so you don't have to. Plus your code won't crash when you get more than 20 treasures!

Choose a class depending on the class' attribute

I want to write a method in java that will select certain words based on an input.
For example, if the choices were a dog, cat, lizard, eagle
and someone types in wings, it'll check to see if the choices have that attribute.
I don't know how complex this is but we've learned for loops, return, if, else and scanners so far.
You can probably maintain a list of attributes for each object, then check if the user typed attribute is part of the list for all object types you have in hand.
I suggest you look at the ArrayList JavaDoc, you will need to use it to maintain the list of attributes. If you don't feel at ease with using an ArrayList object to hold onto your attributes, you may want to use a String array instead, which will work fine too. You will also need to defined a class hierarchy and define a method that will be available in all subclasses (here's a tutorial on inheritance).
Edit
I posted this first answer before reading the comments.
If your only assignment is to provide a list of components that freeze at the user specified temperature, then a list of attributes isn't necessary. You can define a super class (lets say Element) that will define an abstract method public int getFreezingTemperature (). Then, in all subclasses, you will have to implement this method. As an example, if you create a class Water:
public class Water extends Element {
#Override
public int getFreezingTemperature () {
return 0;
}
}
And repeat the same for every element you have to create. Once you are done, whenever a user inputs a temperature, you can query your elements via the method getFreezingTemperature (), and whenever the returned temperature is above the user specified temperature, add it to a list of elements that freeze at the specified temperature.
I'm attempting to answer the substance-temperature question you mentioned in your comment. You could make an arrays as such:
String[] substances = new String[number of substances given];
Then place the substances into the array in the same order that they are given in the assignment. You can then check the user's input and determine at which index the name of the substance corresponding with their input is. For example:
//code to initialize array of substances goes here, call it "substArray"
//code to make scanner goes here, call it "scan"
int temp = scan.nextInt();
if(temp == -100)
{
System.out.println(substArray[index of substance corresponding with -100]);
}
else if...
...
This seems to be a very messy and a not very elegant program to write without use of separate classes, but hopefully this is within the range of your current knowledge and understanding.
I hope this helps,
Tyler
Edit: after reading your comments, it looks like you're going to want to do something like this.
//create your scanner, using whatever resource you are told to use
int temp=scanner.readInt()
//read in the given temperatures
if(substance1freezingpoint > temp){
System.out.println("substances 1 will freeze at " + temp);
}
if(substance2freezingpoint > temp){
System.out.println("substance 2 will freeze at " + temp);
}
....
A couple of things to note about that implementation.
It assumes that more than one substance can freeze at temp. If that isn't the case, you're going to want to use else ifs. As a question to test your learning: why is that?
It doesn't store which substances will freeze at a certain temperature, it just prints them out to the screen. How would you modify this to store the substances which meet the criteria
It doesn't deal with boiling points, but it's a pretty easy modification to make it do that.
So, does that code at least get you off on the right foot, or does it not satisfy what the problem is asking?

Categories