问题来源: 数据库中有两张表 一张题目表 一张选项表 题目表中存放着选项表中正确选项的id(List存放) answerList
获取到所有选项表之后 想要知道哪几个选项是正确选项 要提取正确选项的名称 使用正确选项answerList的contains方法
每一个选项判断id 是否在 正确答案的选项中
// 查询出所有选项
List<TopicOptionsDO> options = topicOptionsMapper.selectList(TopicOptionsDO::getSubjectId, subjectDO.getId());
// 正确答案的list
List<Long> answerList = subjectDO.getSubAnswerList();
collect = options.stream().filter(option -> {
// 选项id
Long id = option.getId();
// 判断是否存在
boolean contains = answerList.contains(id);
System.out.println(answerList);
System.out.println("contains = " + contains+" "+"id="+id);
return contains;
}).map(TopicOptionsDO::getOptionName).collect(Collectors.toList());
因为这个 collect 总是为 0 很是疑惑 便输出看下
[5, 6, 7]
contains = false id=5
[5, 6, 7]
contains = false id=6
[5, 6, 7]
contains = false id=7
[5, 6, 7]
contains = false id=8
[2]
contains = false id=1
[2]
contains = false id=2
[2]
contains = false id=3
[2]
contains = false id=4
[5,6,7] 是answer 判断5是否在这个list中 居然是false ?????
两个明明都是Long类型 查看了contains 的源码
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
// 如果里面有null 的值 那么 查询list中是否为null
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
// 不为null 时 循环遍历数组元素 与o的equals进行比较
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
查看一下Long类型的equals方法
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is a {@code Long} object that
* contains the same {@code long} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
可以看出 这个Long的equals 是将 比较对象转换成Long对象然后取longValue()值 如果相等 那么就是true
dubug一圈之后 发现 不走上述equals 的13行代码 于是我将 answerList中的元素拿出来和第一个 选项的值比较
answerList -> [5,6,7]
options.get(0) -> 5
options.get(0) -> 5
for (Long aLong : answerList) {
TopicOptionsDO topicOptionsDO = options.get(0);
System.out.println("topicOptionsDO.getId() = " + topicOptionsDO.getId());
System.out.println("aLong = " + aLong);
System.out.println("----------");
System.out.println(aLong instanceof Long);
System.out.println(topicOptionsDO.getId() instanceof Long);
System.out.println("----------");
System.out.println(aLong==topicOptionsDO.getId());
System.out.println(aLong.equals(topicOptionsDO.getId()));
}
本想着看看结果 让我发现了意外
这下大家应该知道怎么个事了 .......
数据库类型 json java类型 List<Long>
序列化回来 泛型是Long 但是实际是Integer
使用fori 循环 遍历new 一个新的arrayList 暂时不知有什么其他的好方法 希望评论建议建议