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并返回与该对象关联的userID。
迷茫很多,并希望得到一些帮助来开始解决这个问题。
谢谢!
答案 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
}
}
答案 1 :(得分:1)
我想这种方法可以解决你的问题。希望你在socialMediaAccount课程中有吸气剂。
public String getuserID(ArrayList<SocialMediaAccount> socialMediaAccounts,String websiteName){
for(SocialMediaAccount s:socialMediaAccounts){
if( s.getWebsiteName().equalsIgnoreCase( websiteName)){
return s.getUserID;
}
}
return "no user found";
}
答案 2 :(得分: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;
}
}
答案 3 :(得分:1)
如果您的列表中有很多项目并且您正在进行大量搜索,那么使用网站名称作为密钥的HashMap
会更快。
答案 4 :(得分:0)
I think what you will want
for (SocialMediaAccount socialMediaAccount: socialMediaAccounts) {
if (socialMediaAccount.getwebsiteName() == your_website_search_name) {
return socialMediaAccount.getId();
}
}
return null;