Results 1 to 5 of 5
  1. #1
    syle_q is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default converting array to arraylist

    How can I write code with the same functionality as this:

    Java Code:
      public void addCreature(Creature a) {
            for (int i = 0; i < creatures.length; i++) {
                if (creatures[i] == null) {
                    creatures[i] = a;
                    a.room = this;
                    break;
                    
                }
            }
        }
    but instead of using a simple array named creatue, i need to use an arraylist containing Creature objects?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    If you have

    Java Code:
    List<Creature> creatures = new ArrayList<Creature>();

    then you can use the fact that lists have a size() method that behaves somewhat like the length member of an array. ANd get()/set() methods that allow access to the array elements.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    After getting the array you can use Arrays.asList().

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    But note that replacing the first null element of list is not something that is forced on you (as it is with arrays because they have fixed size). More commonly if you want to put something into a list you just add() it.

  5. #5
    syle_q is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

Similar Threads

  1. Converting Arraylist to String array
    By ankit1801 in forum New To Java
    Replies: 3
    Last Post: 03-23-2011, 11:07 AM
  2. Converting an array program to ArrayList
    By Adomini in forum New To Java
    Replies: 4
    Last Post: 10-13-2010, 08:22 PM
  3. Converting ArrayList to Array
    By vasavi.singh in forum New To Java
    Replies: 1
    Last Post: 02-23-2009, 03:34 PM
  4. Converting ArrayList to Array
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-13-2007, 11:41 AM

Posting Permissions

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