简体   繁体   English

用Java返回一个对象

[英]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. 我想根据其“ description”属性在数组中找到一个对象。

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: 或者,如果您确实想拥有一个Objects数组,则该方法的返回类型必须为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. 您不能在通用对象上调用getDescription。

You want your ArrayList to be composed of a specific type of Object, that has the property description. 您希望ArrayList由具有属性描述的特定类型的Object组成。

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: 现在,您可以创建这种类型的ArrayList,例如:

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: 您的迭代代码已损坏,因为您始终只检查第一个元素,如果不是您要查找的内容,则返回null,您想要的是这样的:

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. 请注意,通过这种方式,您将遍历整个列表,并且只有在循环结束时才返回null。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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