[英]Return an Object in Java
我一直在努力尋找如何返回對象。
我有以下對象數組。
ArrayList<Object> favourites;
我想根據其“ description”屬性在數組中找到一個對象。
public Item finditem(String description) {
for (Object x : favourites) {
if(description.equals(x.getDescription())) {
return Object x;
else {
return null;
有人可以告訴我如何編寫此代碼。 謝謝。
使用泛型:
ArrayList<Item> favourites;
public Item finditem(String description) {
for (Item x : favourites)
if(description.equals(x.getDescription()))
return x;
return null;
}
或者,如果您確實想擁有一個Objects數組,則該方法的返回類型必須為Object:
public Object findItem(String description)
但實際上您希望收藏夾成為項的數組列表!
您不能在通用對象上調用getDescription。
您希望ArrayList由具有屬性描述的特定類型的Object組成。
由於您有班級項目:
public class Item {
private String description;
public String getDescription(){
return description;
}
... other methods here
}
現在,您可以創建這種類型的ArrayList,例如:
List<Item> myList = new ArrayList<Item>();
並以與您執行操作相同的方式對其進行迭代……幾乎。
您的迭代代碼已損壞,因為您始終只檢查第一個元素,如果不是您要查找的內容,則返回null,您想要的是這樣的:
for (Item x : favourites) {
if(description.equals(x.getDescription())) {
return x;
return null;
請注意,通過這種方式,您將遍歷整個列表,並且只有在循環結束時才返回null。
ArrayList<Item>
或將返回類型更改為Object
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.