Results 1 to 11 of 11
  1. #1
    Neilos is offline Member
    Join Date
    Aug 2011
    Posts
    10
    Rep Power
    0

    Default How to iterate over objects in a class?

    Hello,

    If I create a class, let's say it is called 'Vehicle'. Vehicle has some fields in it, varOne, varTwo, varThree.

    Java Code:
    public class Vehicle {
       public float varOne;
       public float varTwo;
       public float varThree;
       public Vehicle (float one, float two, float three) {
          varOne = one;
          varTwo = two;
          varThree = three;
       }
    }
    If I then create 10 instances of Vehicle,
    Java Code:
    vehicleOne = new Vehicle(1,2,3);
    ...
    vehicleTen = new Vehicle(28,29,30);
    How do I then iterate over all ten Vehicles doing things with all their variables? ( eg. vehicleSix.varTwo )

    My initial thought was using a for each loop but in my google'ing I found lots of people itterating over arrays with iterator().

    What is the best way to do this (I haven't yet been able to even get a working test example, I'm so lost lol).

    Thanks for any help.
    Last edited by Neilos; 08-18-2011 at 04:40 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default

    What is the best way to do this
    What determines "best"?
    Fewest number of statements. Least likely to be miscoded. Fastest execution time.
    Easiest to understand when read.

    You don't show what kind of container you are putting the Vehicle objects in. That can determine how you iterate thru them.
    The way you have coded the references to the objects, would not allow you to iterate thru them because each object is referenced by an independently named variable. These variables would have to be used by using each of their names separately.

  3. #3
    Neilos is offline Member
    Join Date
    Aug 2011
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    These variables would have to be used by using each of their names separately.
    I feared as much. So it seems I would need a new way to make the objects, I am only a beginner with Java so if you could show me how?

    Quote Originally Posted by Norm View Post
    What determines "best"?
    I will perhaps have upwards of 200 objects each with approx. 10 fields that will need to be calculated each frame (it is a game I am making). So I suppose the fastest execution time would be the 'best' way, but I am happy with just a way that works if nothing else.

    The way I have it at the moment I suppose then I'd have to create an array and add the object name to the array when it is created and remove it from the array when it is destroyed and then use a for each for each of the object names in the array to update their respective fields. This sounds like a horribly inefficient way to do things to me, am I correct? Is there a better (read faster) way to accomplish this?

    Thanks

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default

    create an array and add the object name to the array
    That would allow you to iterate over the contents of the array.

    add the object name to the array when it is created and remove it from the array when it is destroyed
    If you are going to be changing the contents of the array, then perhaps an ArrayList would be a better place to store the objects. It has many methods for working with its contents.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default

    create an array and add the object name to the array
    That would allow you to iterate over the contents of the array.

    add the object name to the array when it is created and remove it from the array when it is destroyed
    If you are going to be changing the contents of the array, then perhaps an ArrayList would be a better place to store the objects. It has many methods for working with its contents.

  6. #6
    Neilos is offline Member
    Join Date
    Aug 2011
    Posts
    10
    Rep Power
    0

    Default

    I have been looking into ArrayList() and I am having great trouble with it. Could you please help me to get it working?

    I have so far come up with this... (this is actually a quick mock up of what I have done as my code is way bigger and more complicated, well tedious)

    Java Code:
    public class Game {
    	public ArrayList myArrayList;
    	public static void main(String[] args) {
    		myArrayList = new ArrayList();
    		if (vehicleOne == null) {
            		vehicleOne = new Vehicle(1, 2, 3)
    		}
    		if (vehicleTwo == null) {
            		vehicleTwo = new Vehicle(4, 5, 6)
    		}
    		myArrayList.add(vehicleOne);
    		myArrayList.add(vehicleTwo);
    		for (int i = 0; i < myArrayList.size(); i++) {
    			System.out.println("varOne: " + myArrayList[i].one);
    			System.out.println("varTwo: " + myArrayList[i].two);
    			System.out.println("varThree: " + myArrayList[i].three);
    		}
    	}
    }
    I get some odd warnings in eclipse like

    Java Code:
    Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized
    Also the code has errors in the for loop

    Java Code:
    The type of the expression must be an array type but it resolved to ArrayList
    Also I have read about collections. Should I be using a Collection too? Collections and ArrayLists are thoroughly new and confusing for me.

    Thanks

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default

    When you get errors, please copy and paste here the full text of the error message. Your edited versions of the messages have left out important information.

    The new compilers for java want you to tell it what type of data you are going to put into the ArrayList. There is a new syntax technique called Generics for you to tell the compiler. The syntax is to put the data type in <> following the word ArrayList. For example if you are putting Vehicle objects in an arraylist code it like this:
    ArrayList<Vehicle> ...
    For best information go to this site and Find Generics and read up:
    The Really Big Index

  8. #8
    Neilos is offline Member
    Join Date
    Aug 2011
    Posts
    10
    Rep Power
    0

    Default

    The errors were what was displayed when I hovered over the parts of the code in eclipse. I compiled and ran the code to get the full error text in the console, here it is...

    Java Code:
    Exception in thread "Thread-3" javax.media.opengl.GLException: java.lang.Error: Unresolved compilation problem: 
    	The type of the expression must be an array type but it resolved to ArrayList
    
    	at javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:271)
    	at javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:410)
    	at javax.media.opengl.GLCanvas.display(GLCanvas.java:244)
    	at com.badlogic.gdx.backends.jogl.JoglAnimator.display(JoglAnimator.java:149)
    	at com.badlogic.gdx.backends.jogl.JoglAnimator$MainLoop.run(JoglAnimator.java:186)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.Error: Unresolved compilation problem: 
    	The type of the expression must be an array type but it resolved to ArrayList
    
    	at com.epicspacebattle.EpicSpaceBattle.render(EpicSpaceBattle.java:126)
    	at com.badlogic.gdx.backends.jogl.JoglGraphics.display(JoglGraphics.java:113)
    	at com.sun.opengl.impl.GLDrawableHelper.display(GLDrawableHelper.java:78)
    	at javax.media.opengl.GLCanvas$DisplayAction.run(GLCanvas.java:435)
    	at com.sun.opengl.impl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:194)
    	at javax.media.opengl.GLCanvas$DisplayOnEventDispatchThreadAction.run(GLCanvas.java:452)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: 
    	The type of the expression must be an array type but it resolved to ArrayList
    
    	at com.epicspacebattle.EpicSpaceBattle.render(EpicSpaceBattle.java:126)
    	at com.badlogic.gdx.backends.jogl.JoglGraphics.display(JoglGraphics.java:113)
    	at com.sun.opengl.impl.GLDrawableHelper.display(GLDrawableHelper.java:78)
    	at javax.media.opengl.GLCanvas$DisplayAction.run(GLCanvas.java:435)
    	at com.sun.opengl.impl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:194)
    	at javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:412)
    	at javax.media.opengl.GLCanvas.display(GLCanvas.java:244)
    	at javax.media.opengl.GLCanvas.paint(GLCanvas.java:277)
    	at sun.awt.RepaintArea.paintComponent(Unknown Source)
    	at sun.awt.RepaintArea.paint(Unknown Source)
    	at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: 
    	The type of the expression must be an array type but it resolved to ArrayList
    
    	at com.epicspacebattle.EpicSpaceBattle.render(EpicSpaceBattle.java:126)
    	at com.badlogic.gdx.backends.jogl.JoglGraphics.display(JoglGraphics.java:113)
    	at com.sun.opengl.impl.GLDrawableHelper.display(GLDrawableHelper.java:78)
    	at javax.media.opengl.GLCanvas$DisplayAction.run(GLCanvas.java:435)
    	at com.sun.opengl.impl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:194)
    	at javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:412)
    	at javax.media.opengl.GLCanvas.display(GLCanvas.java:244)
    	at javax.media.opengl.GLCanvas.paint(GLCanvas.java:277)
    	at sun.awt.RepaintArea.paintComponent(Unknown Source)
    	at sun.awt.RepaintArea.paint(Unknown Source)
    	at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    My classes have different names than the code I mocked up, you should be able to tell the differences. Mothership = vehicle

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default

    at com.epicspacebattle.EpicSpaceBattle.render(EpicSpa ceBattle.java:126)
    What is the code at line 126? Does it contain this: myArrayList[i]

    There are methods for getting elements from an arraylist. Read the API doc for the ArrayList class.

    Your syntax is for an array of ArrayLists:
    ArrayList[] myArrayList = new ArrayList[23]; // Create an array of ArrayLists
    myArrayList[i] // reference element i in the array (that element would be an arraylist)

  10. #10
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    For a List, use '.get(i)' instead of '[i]'.

    Fixing the compile errors and warnings in the example you gave gives me this:
    Java Code:
    import java.util.*;
    
    public class Game {
    	public List<Vehicle> myArrayList;
    	public static void main(String[] args) {
    		new Game().f();
    	}
    	private void f() {
    		myArrayList = new LinkedList<Vehicle>();
    		Vehicle vehicleOne = new Vehicle(1, 2, 3);
    		Vehicle vehicleTwo = new Vehicle(4, 5, 6);
    		myArrayList.add(vehicleOne);
    		myArrayList.add(vehicleTwo);
    		for (int i = 0; i < myArrayList.size(); i++) {
    			System.out.println("varOne: " + myArrayList.get(i).one);
    			System.out.println("varTwo: " + myArrayList.get(i).two);
    			System.out.println("varThree: " + myArrayList.get(i).three);
    		}
    	}
    }
    You were missing semicolons, had variable declaration issues, and had issues with 'static'.

    (Given your description of the problem, where one wants to go through the elements of the List and remove some of them, I would generally suggest LinkedList, and using '.iterator()', and using the '.remove()' method on the Iterator. But you need to get somewhat further along with the program before you'll have the problems that those things will fix. )

  11. #11
    Neilos is offline Member
    Join Date
    Aug 2011
    Posts
    10
    Rep Power
    0

    Default

    What is the code at line 126?
    Yes it was the myArrayList[i] in the for loop.

    There are methods for getting elements from an arraylist. Read the API doc for the ArrayList class.
    use '.get(i)'
    You both are saying the same thing and yes it is the solution thanks!

    You were missing semicolons, had variable declaration issues, and had issues with 'static'.
    Yeah I see now, doh! lol but that was just code I wrote into this forum post quickly by hand, not anything I copied and pasted from my code so I didn't actually have any errors (like missing semicolons etc)

    I have working code now though, thanks. I can iterate through instances of my objects calling on the fields of those objects, phew!

    Thanks very much people!

Similar Threads

  1. How to use class objects in arrays
    By dironic88 in forum Eclipse
    Replies: 6
    Last Post: 04-06-2011, 01:34 PM
  2. Replies: 0
    Last Post: 07-13-2010, 06:25 PM
  3. How can I display these objects from another class?
    By xx__rose in forum New To Java
    Replies: 5
    Last Post: 05-07-2010, 08:01 PM
  4. Replies: 1
    Last Post: 01-03-2010, 09:48 PM
  5. Getting objects of a class
    By ravian in forum New To Java
    Replies: 1
    Last Post: 12-04-2007, 12:23 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •