简体   繁体   中英

Return an Object in Java

I've been struggling to work out how to return an object.

I have the following array of objects.

ArrayList<Object> favourites;

I want to find an object in the array based on it's "description" property.

public Item finditem(String description) {

for (Object x : favourites) {
   if(description.equals(x.getDescription())) {
      return Object x;
   else {
      return null;

Can someone please show me how I would write this code. Thanks.

Use generics:

ArrayList<Item> favourites;

public Item finditem(String description) {

  for (Item x : favourites)
    if(description.equals(x.getDescription()))
      return x;

  return null;
}

Or if you really do want to have an array of Objects, the return type of the method must be Object:

public Object findItem(String description)

but it really looks like you want favourites to be an arraylist of Items!

You can't call getDescription on a generic Object.

You want your ArrayList to be composed of a specific type of Object, that has the property description.

Since you have your class Item:

public class Item {
    private String description;

    public String getDescription(){
        return description;
    }

   ... other methods here
}

Now you can create an ArrayList of this type, such as:

List<Item> myList = new ArrayList<Item>();

And iterate over it the same way you're doing... almost.

Your iteration code is broken, since you'll always just check the first element, and return null if it's not what you're looking for, what you want is something like:

for (Item x : favourites) {
  if(description.equals(x.getDescription())) {
    return x;

return null;

Notice that this way you'll iterate over the entire list, and only if you reach the end of the cycle will you return null.

ArrayList<Item>或将返回类型更改为Object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM