Array of ArraList?

Hello guys! :slight_smile:

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! :slight_smile:

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 :wink:


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 :slight_smile:

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 :frowning:

I originally had only one ArrayList where I put EVERY entity I had:

  • Enemies
  • Fx’s
  • Player
  • GUI (not really a GUI yet, just a border and a place to display info, take a look at my showcase here
  • Shots
  • PowerUps
  • Background

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). :slight_smile:

What do you think I should do? The collision method is a mess right now :frowning:

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.