[英]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.