Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: FAQ: find variable in an array of objects

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Thanked 0 Times in 0 Posts

    Default FAQ: find variable in an array of objects

    My brain's gone finishing this morning, so I need a bit of help. Let's say I have a class that looks like this:
    Class Foo
       int bar;
       int mooose;
       void Foo(int bar, int moose)
           this.bar = bar;
           this.moose = moose;

    And then somewhere I create an array of objects, fooObj, of the type Foo and populate the variables of all objects in the array. How would I find which object has moose=42?

  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Thanked 619 Times in 561 Posts
    Blog Entries

    Default Re: FAQ: find variable in an array of objects

    The simple answer is to create a getter method for moose and see if that value is 42. If it's not, look at the next fooObj to see if it's moose is 42.

    public int getMoose()
         return moose;

    Note: If you have multiple fooObj's in the list with moose=42, this method will return the first one it finds. Depending on your application, this may or may not be what you want.

Similar Threads

  1. Objects
    By chronoz13 in forum Java Theory & Questions
    Replies: 5
    Last Post: January 20th, 2010, 12:50 PM
  2. cannot find symbol variable radius?
    By noobish in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 4th, 2009, 10:29 AM
  3. Replies: 5
    Last Post: September 19th, 2009, 06:48 AM
  4. Assigning variable to an Array
    By sridevi in forum Collections and Generics
    Replies: 3
    Last Post: August 10th, 2009, 10:58 PM
  5. [SOLVED] Creation of objects of Array in Java
    By sadi_shihab in forum Collections and Generics
    Replies: 4
    Last Post: July 9th, 2009, 01:38 PM