2017-04-02 113 views
1
private ArrayList<SocialMediaAccount> socialMediaAccounts; 

public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel) 
{ 
    SocialMediaAccount object = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel); 
    socialMediaAccounts.add(object); 
} 

我有這個ArrayList,我需要尋找一個特定websiteName並返回與對象相關聯的用戶ID。 感到困惑了很多,希望能夠幫助您解決這個問題。 謝謝!搜索字符串一個ArrayList並返回另一個關聯的字符串

+0

嗨,請參閱我在解決方案中留下的評論。 –

回答

2

你可以通過ArrayList和檢查websiteName存儲在列表這樣的websiteName匹配:

for(int i = 0; i < socialMediaAccounts.size(); i++) 
    if(socialMediaAccounts.get(i).getWebSiteName().equals(the_website_you_arelooking_for){ 
    return socialMediaAccounts.get(i).getUserId 
    } 
} 
+0

'if需要一個額外的權利paren,但總的前提看起來很合理。 –

+0

嗨,我必須使用的頭部代碼是'公共字符串getSocialMediaID(字符串websiteName)' –

+0

嗨,不,我不太確定如何使用您提供的代碼或Rahul的解決方案使用該頭。 –

0
I think what you will want  

for (SocialMediaAccount socialMediaAccount: socialMediaAccounts) { 
      if (socialMediaAccount.getwebsiteName() == your_website_search_name) { 
       return socialMediaAccount.getId(); 
      } 
     } 
     return null; 
+0

'=='不會這樣做;你需要使用'socialMediaAccount.getWebSiteName()。equals(your_website_search_name)' –

1

我想這個方法可以解決你的問題。希望你的社交媒體帳戶類中有getter。

public String getuserID(ArrayList<SocialMediaAccount> socialMediaAccounts,String websiteName){ 
for(SocialMediaAccount s:socialMediaAccounts){ 
    if(s.getWebsiteName().equalsIgnoreCase(websiteName)){ 
     return s.getUserID; 
    } 
} 
return "no user found"; 
} 
+0

Rajith我認爲這個答案不正確。因爲如果第一個條件失敗,它將返回**沒有用戶發現**並退出循環。你不覺得嗎? –

+0

@法拉茲你是對的..我修改了代碼。 –

+0

'if'結尾的{}'可疑;不應該只是'{'? –

1

這應該有效。

//This method will return the userID associated with the given target websiteName. 
//Insert it where you need it. 
public String search(String targetWebsiteName){ 
    //loop through each account in your list. 
    For(SocialMediaAccount acc: socialMediaAccounts){ 
     SocialMediaAccount tempObject = acc; 
     //check for websiteName 
     if(tempObject.getWebsiteName().equals(targetWebsiteName)) return tempObject.getUserID(); 
    } 
return null; 
} 


//Add these methods to your SocialMediaAccount class 
class SocialMediaAccount{ 

     //Getters for object variables 
     String getWebsiteName(){ 
      return websiteName; 
     } 

     String getUserID(){ 
      return userID; 
     } 
} 
1

如果你有很多你的列表中的項目和您使用的網站名稱爲重點,會快很多做了很多的搜索,一個HashMap

相關問題