Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

iteration newby question

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
IT
Hallo,

I have an arraylist containing objects. I would like to iterate it and confront one of the properties ("name") of the object with a string. If they match I return the object.
I don't know how to compare the present object property of the iteration with the string, and how to return the matching one.

The code I have till now:
Code:
public myObject find(String criteria)
{
  int i=1;
  Iterator<myObject> it = this.myArrayList.iterator();
  while (it.hasNext())
  {
    if (((it.next())).equals(criteria)¨
      {return ...?...}
    else
      i++;
  }
 
Assuming the class myObject (should probably be MyObject to follow naming conventions) has a public getName() method that returns a String, and you want to return null if there is no match,
Code:
public myObject find(String criteria)
{
  int i=1;
  myObject temp = null;
  Iterator<myObject> it = this.myArrayList.iterator();
  while (it.hasNext())
  {
    temp = it.next();
    if (temp.getName()).equals(criteria)¨
      {break;}

  }
  return temp;

-----------------------------------------
I cannot be bought. Find leasing information at
 
Or you could do the following:

Code:
public myObject find(String criteria) {
   for (myObject obj : myArrayList) {
      if (obj.getName().equals(criteria))¨
         return obj;
   }
   return null;
}
 
It depends on how the name property is coded.

If you want to keep the property private you can code a isSameName method that will compare the values.

Cheers,
Dian
 
A List of matching results can be more appropriate...
Code:
public List <MyObject> find (String criteria)
{
	List <MyObject> results = new ArrayList <myObject> ();

	for (MyObject mo : myArrayList)
	{
		if (mo.getName ()).matches (criteria))
		{
			results.add (mo);
		}
	}
	return results;
}

	// usage:
	List <MyObject> l1 = find (".*foo.*");
	for (MyObject myObject : l1)
	{
		myObject.doSomething ();
	}
...and is more easy to use, than a method which might return null (NullPointerException) - an empty list is a natural thing.

Yes - you want to change myObject to MyObject. :)

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top