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.
Related
Let's say for example a vector is composed of some objects, one of type rectangle, some of type triangle, and then circles.
v = [rectangle, triangle, triangle, circle, circle]
The vector's size can change. I can add another circle as so:
v.addElement(circle);
and..
v = [rectangle, triangle, triangle, circle, circle, circle]
but each object type is clustered together like above. It can't be like:
v = [rectangle, circle, circle, triangle, circle, triangle] //<-- can't be.
I know I explained it pretty horrible but hopefully, it's enough to understand my scenario. Now, I want to randomly choose, for example, an object of type circle.
My thought process is to make a separate method that 1, finds the beginning index and 2, find the ending index and then use random functions off of that. Is there a more elegant way to solve this problem of only choosing randomly off of circles?
Use the Collections API:
Collections.shuffle(v);
Object random = v.get(0);
You should use a hashmap and map the object class as the key and a corresponding array of objects of that class. You can yse reflection to get the class name and set as the key, then add the object to the array as the value.
Otherwise you can't group similar objects in the array and choose a random object from a set of similar objects in an array of different classes like you asked... Unless you framed your question incorrectly
This sounds like a fairly simple random pick problem. All you need to do is generate a random number and get that element -
v.get(Random.nextInt(v.size()));
You can potentially use the implements keyword to check if an object is of a type (or a subtype of that type), but this is not a very pretty solution.
The best solution would likely be to control read and write access to this vector; basically, if you have specific methods for inserting the different shapes, you can stay in control and always ensure that things are inserted to the right place. At that point, just store two ints or such to know where the second and third sections start when choosing.
Although personally, I would just use three separate vectors, if that's possible.
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.
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!
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.
How can I fill up two vectors and combine them with each other (either index or an object type in class). I guess if I use index to combine them, then the sorting can be handled with Collections.sort otherwise I have to create a comparator.
We have to code down to the Java 1.4 convention.
To make your imagination easier; it's a grid which has a sorting vector (rows) and a content vector (with all cols). They need to be filled in a vector and sorted.
Context: I have a GridBagLayout containing all components in a wierd order. I need to cycle through all components and fill them in the right grid order (gridx, gridy). For that solution I thought about two vectors, one defines the row and points to the vector containing it's cols. Either the sort will be be resolved while filling the vector or I have to sort it in a second step. I guess for java 4 there is no other approach than two vectors containing an object, right?
The OO solution is to wrap the objects in both vectors in something that implements the comparing and keeps a pointer to the real object. This way, you can sort both vectors independent of each other and use the wrapper to get at the real object.
This is the "Decorator" design pattern.
Please let me know if I understand. As input, you're given two vectors. The first is an ordered list of row numbers that reference indices in the second vector. The second vector is a list of somethings. You would like a vector that contains the same objects as the second vector, but sorted in the order described in the first vector.
Assuming that's what you're trying to do, this is how I'd do it:
public class ThisHadBetterNotBeAHomeworkAssignmentYoungMan {
public Vector orderContent(Vector indices, Vector content) {
Object[] orderedStuff = new Object[content.size()];
for( int i=0; i < indices.size(); i++ ) {
orderedStuff[i] = content.get(((Integer)indices[i]).intVal());
}
return new Vector(orderedStuff);
}
}
//Note that this is pretty rough code, and I have neither executed it nor bothered checking to see if you can pass an array of stuff into a Vector as a constructor, but you get the idea.
//note also that I'm not sure exactly what you're asking and could be entirely wrong.