[英]Checking if arraylist object exists
好吧,我的問題是這個。
我的班級消息包含:-id-消息-[用戶]
我的班級用戶包含:-id-名稱
這是將信息添加到arrayList的方式: http ://pastebin.com/99ZhFASm
我有一個包含ID,消息,用戶的arrayList。
我想知道我的arrayList是否已經包含“用戶”的ID
注意:已經嘗試使用arraylist.contains
(Android)
由於您有對象Message
具有唯一的標識符( id
),因此請不要將其放在ArrayList
,請使用HashMap
或HashSet
。 但是首先,您需要在該對象中創建equal()和hashCode()方法:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Message message = (Message) o;
return id == message.id;
}
@Override
public int hashCode() {
return id;
}
這樣,您可以利用地圖和集合的優勢。 因此,請執行以下操作:
User user = new User();
user.setId(1);
user.setName("stackover");
Message msg = new Message();
msg.setid(10);
msg.setmessage("hi");
msg.setUser(user);
HashMap<Integer, Message> map = new HashMap<>();
map.add(new Integer(msg.getId()), msg);
boolean isItInMapById = map.containsKey(new Integer(10));
boolean isItInMapByObject = map.containsValue(msg);
如果您需要消息的ArrayList
,只需執行以下操作:
ArrayList<Message> messages = new ArrayList<>(map.values());
如果需要,您還可以獲取ID列表:
List<Set<Integer>> idList = Arrays.asList(map.keySet());
arrayList.stream().anyMatch(item.id == user.id)
如果您使用的是Java 8,則可以編寫如下代碼:
ID theIdWeAreMatchingAgainst = /*Whatever it is*/;
boolean alreadyHasId =
list
.stream()
.anyMatch(m -> m.getId() == theIdWeAreMatchingAgainst);
如果您確實需要具有該ID的消息,
Message[] msgs =
list
.stream()
.filter(m -> m.getId() == theIdWeAreMatchingAgainst)
.toArray(Message[]::new);
Message msg = msgs[0];
如果您使用的是Java 7-,則必須采用舊方法:
public static List<Message> getMessage(ID id, List<Message> list) {
List<Message> filtered = new ArrayList<Message>();
for(Message msg : list) {
if(msg.getId() == theIdWeAreMatchingAgainst) filtered.add(msg);
}
return filtered;
}
因此,您的問題和代碼似乎並不對應。 您具有消息的ArrayList,其中消息包含ID,消息字符串和用戶對象。 您正在為該消息應用一個ID,並為用戶應用另一個ID。 您要確保ArrayList與ID匹配,可以通過兩種方法進行。
你可以做這樣的事情
boolean matchMessageId = true;
int idToMatch = [some_id];
for(Message message : arrayList){
int currId = matchMessageId? mesage.id: message.user.id;
if(currId == idToMatch){
return true;
}
}
return false;
但是,這似乎更適合於HashMap或SparseArray之類的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.