我有一个参数为List<Long> l的函数。
函数中有一个if语句,我必须对存储在List<Long> l中的每个值进行迭代。
我想这么做:
    public void myFunction(final List<Long> l) {
        final int size = l.size();
        for (int i = 0; i < size; i++){
           if (l.get(i) <= 900) {
              ...       
           Log.d("resultL", String.valueOf(l.get(i)));
           } else {
           }
        }
    }这里,resultL只记录了-64338
存储在List<Long> l中的值是[-64338, -15512, -15224, 8344],但是所发生的情况是,if语句只使用-64338并执行逻辑,而不是使用所有的4个值。
更新1
使用@KushPatel的答案,resultL打印出:
D/resultL: -64338
D/resultL: -15512
D/resultL: -15224
D/resultL: -64338
D/resultL: -15512
D/resultL: -15224
D/resultL: -64338
D/resultL: -15512
D/resultL: -15224
D/resultL: -64338
D/resultL: -15512
D/resultL: -15224为什么会发生这种事?
如何对这里存储的所有4个值进行迭代,而不仅仅是一个?
请帮我解决这个问题。
发布于 2016-12-29 13:47:12
据我所知,当你得到所有小于900的值后,你想做些什么。然后,您应该首先将它们放在另一个List中
public void myFunction(final List<Long> l) {
    final int size = l.size();
    List<Long> results = new ArrayList<>();
    for (int i = 0; i < size; i++){
       if (l.get(i) <= 900) {
           results.add(l.get(i));
       } else {
           ...
       }
    }
    // do your thing with results list
}我认为有很多方法可以做到这一点,但这是简单和容易理解的。
发布于 2016-12-29 13:32:04
如果我正确理解,您应该执行一些操作,如果您的所有元素小于或等于900。对吗?试着像这样:
boolean isDataValid = true;
for(Long num : l){
     if (num  > 900){
          isDataValid = false;
     }
}
if(isDataValid){
}else{
}发布于 2016-12-29 14:16:18
几个问题:
1)使用长表示负数
它的最小值为0,最大值为264-1。当需要比int提供的值范围更广的值时,请使用此数据类型。
2)你正在检查一个数字是否小于900
if (l.get(i) <= 900)
负数会溢出,变成正数,Java (就像现在大多数的计算机体系结构一样)使用的是二补,所以你的一些负数会变成大于900的数字,不会被打印在屏幕上。
溶液
1)使用整数而不是长
public void myFunction(final List<Integer> l) {
final int size = l.size();
List<Integer> results = new ArrayList<>();
for (int i = 0; i < size; i++){
   if (l.get(i) <= 900) {
       results.add(l.get(i));
   } else {
       ...
   }
}https://stackoverflow.com/questions/41380665
复制相似问题