java根据其中一项将ArrayList类过滤为另一个类
我试图对我的commentList
进行排序,结果是itemList
,其中只有最后一个值itemPosition
等于当前位置的项。我有一个用于列表项的类,有4个值:
class CommentItem {
int profile;
String user;
String message;
int itemPosition;
}
我试图使用这段代码对其进行排序,但它只是添加了正确数量的值,而不是我想要的实际值
for (CommentItem item : commentList) {
if (item.getItemPosition() == position) {
itemList.add(new CommentItem(
commentList.get(position).getProfile(),
commentList.get(position).getUser(),
commentList.get(position).getMessage(),
commentList.get(position).getItemPosition()
));
}
}
这是commentList
:
commentList = new ArrayList<>();
commentList.add(new CommentItem(R.drawable.circleicon, "User0", "Message0", 1));
commentList.add(new CommentItem(R.drawable.circleicon, "User1", "Message1", 2));
commentList.add(new CommentItem(R.drawable.circleicon, "User2", "Message2", 3));
commentList.add(new CommentItem(R.drawable.circleicon, "User3", "Message3", 4));
commentList.add(new CommentItem(R.drawable.circleicon, "User4", "Message4", 1));
commentList.add(new CommentItem(R.drawable.circleicon, "User5", "Message5", 2));
commentList.add(new CommentItem(R.drawable.circleicon, "User6", "Message6", 3));
commentList.add(new CommentItem(R.drawable.circleicon, "User7", "Message7", 4));
commentList.add(new CommentItem(R.drawable.circleicon, "User8", "Message8", 0));
带有位置的结果itemList
显示以下项目:
commentList.add(new CommentItem(R.drawable.circleicon, "User0", "Message0", 1));
commentList.add(new CommentItem(R.drawable.circleicon, "User1", "Message1", 2));
我还尝试了所有这些代码:
for (CommentItem item : commentList) {
if (item.getItemPosition() == position) {
itemList.add(new CommentItem(
item.getProfile(), item.getUser(),
item.getMessage(), item.getItemPosition()
));
}
}
for (CommentItem item : commentList) {
if (item.getItemPosition() == position) {
itemList.add(item);
}
}
for (CommentItem item : commentList) {
if (item.getItemPosition() == position) {
itemList.add(commentList.get(commentList.indexOf(item)));
}
}
同样的结果
提前谢谢
# 1 楼答案
首先,正确声明注释列表以避免编译错误:
此外,写以下内容更有效:
而不是
.add() .add() .add()...
或者,您可以使用for循环来创建所有这些新的注释项。由于您正在生成user1、user2等。。。,只要写下:
最后,回答你的问题:
其中最重要的部分是
commentList.get(commentList.size()-1))
,这是获取列表中最后一个元素的简单方法