Results 1 to 3 of 3
  1. #1
    Globular is offline Member
    Join Date
    May 2011
    Posts
    5
    Rep Power
    0

    Default Array index from element?

    Is it possible to get the index number from an element in that array? I was trying to make a numbered list with a for loop using the array index instead of a seperate incrementing variable.

    For example:

    Java Code:
    String[] trees = {"Maple", "Pine", "Burch"}
    Can I do something like... trees.index("Maple") to get the index, in this case 0?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,452
    Rep Power
    20

    Default Re: Array index from element?

    You can iterate over the array in a for loop, and test each element in turn for equality. When the equality test passes, the value of the loop index is what you want.

    Alternatively, you can use a java.util.List instead of an array. List has a method that can serve your purpose.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Globular is offline Member
    Join Date
    May 2011
    Posts
    5
    Rep Power
    0

    Default Re: Array index from element?

    Thanks, I'll give that a try.

Similar Threads

  1. Pick random array index and change the element value
    By Space Ranger in forum New To Java
    Replies: 8
    Last Post: 03-29-2011, 11:18 PM
  2. Replies: 23
    Last Post: 09-07-2010, 09:12 PM
  3. Replies: 2
    Last Post: 09-06-2010, 02:03 AM
  4. Replies: 1
    Last Post: 03-31-2009, 07:40 AM
  5. Max element in an Array
    By mew in forum New To Java
    Replies: 5
    Last Post: 12-03-2007, 06:26 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
  •