簡體   English   中英

在arraylist中編輯元素,找到索引?

[英]Edit element in arraylist, find index?

我將創建兩種創建和更改客戶資料的方法。 創建配置文件沒有問題。 那里一切似乎進展順利。 但是,當我隨后進入並更改配置文件時,我發現它不起作用。

indexOf()給我-1,即使我搜索的值可用:S

有人對此有很好的解決方案嗎?

問題出在editProfile方法中!

public class Profile{
    String name;
    long id;
    int accNr = 1000;
    double balance;
}

ArrayList<Profile> profileList = new ArrayList<Profile>();

public boolean newProfile(long id, String name, int amount){
    Profile newProfile = new Profile();
    Profile accNr = new Profile();

    int ACC = accNr.accNr++;

    newProfile.accNr = ACC;
    newProfile.id = id;
    newProfile.name = name;
    newProfile.balance = amount;

    profileList.add(newProfile);

    return true;
}

public void editProfile(long id, String newName){
    int ID = (int)id;
    System.out.print(ID);
    int index = profileList.indexOf(id);
    System.out.print(index);

    profileList.get(index);
}

indexOf方法將使用equals方法確定列表中是否存在您的Profile 您必須重寫Profileequals方法以返回正確的結果。

其次,它不會找到您的Profile ,因為您將long傳遞給indexOf ,並且列表中不會找到longLong 如果必須long檢索Profile ,則使用Map<Long, Profile>而不是ArrayList<Profile>更有意義。 然后,您可以調用get(id)來檢索Profile 通常,如果覆蓋equals ,則應該覆蓋hashCode方法 ,但是由於此處沒有將Profile用作鍵,因此沒有必要。

profileList包含Profile實例,並且您試圖獲取long的索引。

  • 一種解決方案是在Profile類中重寫equals方法。
  • @Override
    public boolean equals(Object obj) {
        ...
    }
    

  • 另一個解決方案(不太推薦)是遍歷profileList元素並手動檢查匹配項,例如:
  • for (Profile element : profileList)
        if (element.getID() == id)
            ...
    

    可能您的Profile需要覆蓋equals和hashCode方法。 然后可以生成Eclipse,就像舉個例子:

    public class Profile {
    String name;
    long id;
    int accNr = 1000;
    double balance; 
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + accNr;
        long temp;
        temp = Double.doubleToLongBits(balance);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + (int) (id ^ (id >>> 32));
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Profile other = (Profile) obj;
        if (accNr != other.accNr)
            return false;
        if (Double.doubleToLongBits(balance) != Double
                .doubleToLongBits(other.balance))
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    

    }

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM