Hello guys!
I have a quick question, how do I do an array of ArraList?
Something like:
public ArrayList[] layers = new ArrayList();//Obviously wrong code
???
Hello guys!
I have a quick question, how do I do an array of ArraList?
Something like:
public ArrayList[] layers = new ArrayList();//Obviously wrong code
???
Same way you would declare an array of any other type.
ArrayList[] arrayOfArrayList = new ArrayList[size];
for(int i = 0; i < size; i++) {
arrayOfArrayList[i] = new ArrayList();
}
However, if youâre planning on using the Generic functionality of the ArrayList (ArrayList) you cannot use an array of arraylists for it. :3
Thanks UprightPath for your quick answer :), however I have some issues:
I have something like this:
public ArrayList[] ArrayOfArrayList = new ArrayList[4];
...
...
if (ArrayOfArrayList[0].isEmpty()){ // And here trows a java.lang.NullPointerException :(
...
...
...
}
What Iâm doing wrong? ???
Thatâs what the:
for(int i = 0; i < size;i++) {
arrayOfArrayLists[i] = new ArrayList();
}
Takes care of. After you initialize the array, you then have to initialize the objects in the array.
An array is just a data structure, something that holds data. Until you assign data to the elements in the array (arrayOfArrayList[i] = something), the values are always going to be null. An array doesnât (really) care what sort of object is placed in it. It doesnât do anything special. It wonât fill itself in with default values (Unless itâs a primitive array, and even then itâs best not to assume).
Thank you very much! That was very clear!
I thought that public ArrayList[] ArrayOfArrayList = new ArrayList[4]; was already initializing every element!
Thank you again! :-*
It is not recommended to use raw types of generic classes, use the generic way:
ArrayList<SomeType>[] myList = new ArrayList<SomeType>[10];
Does not work, ra4king!
Does not work.
You cannot instantiate any form of generic array. Any. When you attempt to do that, youâll get an error.
xD Sorry, this is an issue that Iâve had fun dealing with for a long time. Java will not allow you to use any form of Generic realization in an array structure.
It does work.
Initializing generic array however doesnt (T[]) which is probably what you meant.
To follow up on that comment, to allow for a âGeneric Arrayâ you have to put a bit more work into it. Something likeâŚ
public class GenericArray<Element> {
private Object[] elements;
private final int size;
public GenericArray(int size) {
this.size = size;
elements = new Object[size];
}
public void setElementAt(int index, Element element) {
elements[index] = element;
}
public Element getElementAt(int index) {
return (Element) elements[index];
}
/*
* A bunch of other helper methods here.
*/
}
Iâve been delving around for a while, and this is perhaps the best way to do it because of the way that Java works. However, you have to maintain strict control over the elements array, to ensure that youâll only ever have objects of type Element in it.
After correcting what ra4king wrote (He forgot the [] on the declaration) drop it into an IDE. It will not allow you compile it, giving you the âGeneric Array Creationâ error. Both in Netbeans and in Eclipse. Believe me Iâve tried to make this work.
Er, let me rephrase that bit.
ArrayList<SomeObject>[] arrayOfArrayList; // will work.
arrayOfArrayList = new ArrayList<SomeObject>[size]; // will not work.
You cannot create a generic array that way.
If you can get an object of the generic type prior to creating the array, you can do this.
T object = ... // Some code to get the object
T[] elements = (T[]) Array.newInstance(object.getClass(), size);
So, in this case, he can do this sort of mumbo-jumbo:
ArrayList<Object> object = new ArrayList<Object>();
ArrayList<Object>[] myList;
myList = (ArrayList<Object>[]) Array.newInstance(object.getClass(), 10);
myList[0] = object;
for(int i = 1; i < size; i++) {
myList[i] = new ArrayList<Object>();
}
Which is probably the best he can do. Because for the most part, Generics are not meant to work with arrays. Itâs a known fact that they donât play nicely together and probably never will.
On a side note, is anyone elseâs code-block formatting off? Mineâs got everything on the wrong line number. O.o Like shifted one down, with a leading blank.
I donât even remember seeing line numbers before; maybe theyâre a new feature and still not perfectly implemented?
Nah, theyâve been there for a while. Theyâre just a very light grey.
;D Iâve been expecting your reply. You cannot instantiate an array of generic type. However, you can instantiate an array of a known type regardless of whether it uses a generic type or not
ArrayList<SomeType>[] myList = new ArrayList<SomeType>[10];
^^ this compiles, try it!
Heh, maybe I just now started noticing them because theyâre off.
Now that Iâve sufficiently derailed the thread, you may continue discussing arrays of ArrayListsâŚ
/walks off in shame
Nope! Still doesnât work.
Iâve got this sitting in my IDE and itâs giving me the generic array error. :3
ArrayList<Object>[] myList = new ArrayList<Object>[10];
ArrayList is not generic.
ArrayList is considered generic for the purpose of array instantiation.
AnythingHere is generic, and is treated as such for object and array instantiation.
I did this and works just fine
public ArrayList[] layers = new ArrayList[size];
Now, the hole point of this was to do some sort of âlayersâ to draw my things in some order:
layers
layer 0 = backgrounds
layer 1 = enemies
layer 2 = player
layer 3 = shots, fxs, power ups.
layer 4 = gui
I feel that it ainât the best way to do it, but Iâm working on while learning!
This way I can, for example, keep things organized and keep everything âaboveâ backgrounds and âbelowâ the gui. Is this ok?
BTW, I use brute force collision check to see if a shot collides with an alien for example. I used to check only one arraylist, but now I have to check 3:
layer 1 with layer 2 and 3, layer 2 with layer 1 and 3 and layer 3 with layer 1 and 2.
Any tips to make this simpler? ???
Wrong on many levels. Honestly, what is the compulsion to use arrays here? Just use a pair of nested Lists and you donât have to juggle around what the rules are. Just STOP MIXING ARRAYS AND GENERICS and everything works out great.
Best way? Perhaps not.
The way that works and that you understand it? Sometimes better than the best way.
However, what youâve got seems ârightâ for a given value of right.
The way you describe it, it sounds like:
A) Enemies cannot collide with each other.
B) Power ups, FX/Shots can collide with enemies.
The only way you could only have to check a single list would be to attempt to consolidate all of that data into a single list some how. Then manage several lists to ensure that removed objects are removed from all. Itâs probably too much work!
However, thatâs for the collision system.
You should be dividing up your logic from your GUI in the first place. Your GUI might read the from the logic portion of your program, but your program should have no knowledge of your GUI (Except through input methods of some sort).
Either way, this is a completely different discussion than the ArrayList issue. :3
Because ArrayLists donât have a sense of bounding/strict indexing.
If youâre not doing lazy initialization, then thereâs no problem.
Object[] array = new Object[10];
ArrayList list = new ArrayList();
Object holderObject;
for(int i = 0; i < 10; i++) {
holderObject = new Object();
array[0] = holderObject;
list.add(holderObject);
}
array[0] == list.get(0);
...
array[4] == list.get(4);
...
array[9] == list.get(9);
If youâre doing lazy initialization, then you have to add code to ensure that you insert âblanksâ to the right depth in the ArrayList whenever you insert anything.
Object[] array = new Object[10];
ArrayList list = new ArrayList();
Object holderObject = new Object();
array[4] = holderObject;
if(list.size() < 4) {
for(int i = list.size() -1; i < 4; i++) {
list.add(null);
}
list.add(holderObject);
} else {
list.remove(4);
list.add(4, holderObject);
}
Really, itâs an issue of arrays being more convenient than a List in bounded/indexed circumstances. If youâre going to attempt to use an ArrayList and bound it/give it strict indexing, youâre going to have to write code that simulates an array anyway.
Well, trying to make my code better, I ended up messing everything
I originally had only one ArrayList where I put EVERY entity I had:
I realized that the order of drawing the entities made some of them be above the others, so I got the idea of sorting the entities so my background really is at the background. After a little while, I had my initEntities ordered so the first entity was my background and then the other entities. I didnât like to have to worry about the order of entities to be drawn like this, so I figured I would implement layers of entities. That way I could do something like Parallax (I think). It worked pretty well on my head, but implementing it is horrible! lol!
So, thatâs what ArrayList[] layers is for. To keep an array of layers where 0 is the farthest and 4 is the nearest (the gui).
What do you think I should do? The collision method is a mess right now
MVC! And no, not Marvel versus Capcom.
Ahem, really, you have to separate your concerns as best you can.
Your logical backend should be decoupled from your user interface front end. What this means is that it to your logic system should not have any idea of how itâs receiving input. You should be able to write various different UIs for your game and it shouldnât require you to rewrite your game to do so.
You do this by refactoring/reengineering your system such that you remove all instances of UI specific data: Images, screen position, input recognizing code (Like hard coding it to recognize a right-keystroke to mean right), etc. You do, however, leave it to ability to provide data about global positioning, some sort of ID to help differentiate it between other objects, etc and methods to manipulate it. Such as âmakeCharacterWalk(Direction)â or something like that. (Think of this as the object that gets âupdatedâ on every tick.)
Then you write your GUI as a separate system. This system will know about your logic system, what data it can read from the system and what data it can provide to the system. This should where you take input/process it into commands. This system is the one that will handle the âlayeringâ required for animating your program. It knows about the background images, the object images, the gui, etc. It knows how what order to draw things, and asks the logic system for information about what in it to draw things. (Think of this as the object that gets ârenderedâ on every tick.)
Really, this is a rather basic description of it, and probably wrong in points. However, you can look up the MVC Pattern/Architecture for more information.