Results 1 to 2 of 2
  1. #1
    elizabeth is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default how to return an object from an arraylist

    How can I return an object from an arraylist given a specific index?

    something like that?
    Java Code:
    private ArrayList container = new ArrayList;
    
    public Test()
    {
    for( int i = 0; i < container.size(); i++)
    object.exampleMethod(container.get(i));
    }

  2. #2
    brianhks is offline Senior Member
    Join Date
    Jul 2007
    Posts
    135
    Rep Power
    0

    Default

    container.get(i) will return the object at the i position in the array list.

    It almost looks like you are wanting to call a method on that object that is returned. To do that you will want to do something like this:
    Java Code:
    //Say the array is containing objects of type MyObject
    ((MyObject)container.get(i)).myMethod();
    A better way is to use the new Java types with your containers. Like so
    Java Code:
    private ArrayList<MyObject> container = new ArrayList<MyObject>();
    
    public Test()
    {
    for( int i = 0; i < container.size(); i++)
      {
      //Now you can do things like this
      container.get(i).myMethod();  
      //Because the container knows it is holding an object of type MyObject
      }
    }

Similar Threads

  1. Replies: 2
    Last Post: 11-26-2010, 03:12 AM
  2. Replies: 2
    Last Post: 04-21-2008, 12:43 PM
  3. Object ArrayList - increment solution needed badly!!
    By rugbyGeek in forum New To Java
    Replies: 4
    Last Post: 03-08-2008, 01:47 AM
  4. object instantiation and arrayList
    By lockmac in forum New To Java
    Replies: 5
    Last Post: 08-09-2007, 07:25 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
  •