Java 在数组列表中查找值 [英] Java Finding a value in arraylist

查看:39
本文介绍了Java 在数组列表中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 arraylist 中添加了一些数字.我想从中找到某个值.例如我有 4、4、9、9、18.我想找到 26 的值.如果 26 > 列表中的最大值,它将显示 18,如果值为 17,它将显示 9,如果值为 5,它将显示 4.还有另一种方法来实现这个搜索,因为线性搜索可能很慢.

I have added few number into the arraylist . I would want to find the certain value from it.Example i have 4,4,9,9,18. I would like to find the value of 26. If 26 > largest value in the list it will display 18 and if value is 17 it will display 9, and if value is 5 it will display 4. Also is there another method to implement this search because liner search might be slow.

search value 26

    [4,4,9,9,18] display 18
    [20,20,29,29,4] display 20
    [28,28,28,1,10] display 28

如果你有这个列表并搜索26,它会输出第一个元素.因为第一个元素是 <= 而不是被搜索的值.

if you have this list and search 26, it will output the first element. because the first element is <= than the value being search.

但当前输出是

value2 的值:9

Value of value2 : 9

    public class Arraylist {

    public static ArrayList<Integer> aList;

    public static void main(String[] args) {
        aList = new ArrayList<Integer>();
        aList.add(4);
        aList.add(4);
        aList.add(9);
        aList.add(9);
        aList.add(18);
        int value = 26;
        int value2 = 0;

        for (int i = 0; i < aList.size(); i++) {
            if (aList.get(i) <= value) {          
                if (i + 1 < aList.size()) {
                    value2 = aList.get(i);
                } else if(i > aList.size()) {
                    value2 = aList.get(i);

                }
            }
        }
        System.out.println("Value of value2 : " + value2);
    }
}

推荐答案

我已经使用数组编写了代码.您可以轻松地将其应用于 ArrayList

I have written the code using an array. You can easily adopt it to ArrayList

int a[] = {28,28,28,1,10};
// int a[] = {20,20,29,29,4}; // other input of yours
// int a[] = {4,4,9,9,18};  

   int x = 26;

   int liVal = -1;
   for(int i=0; i<a.length;i++)
       if(x < a[i]) // if we met a value > x
       {
          if(liVal==-1) // if we could not find any largest value smaller than x
              liVal = a[i]; // return the value > x
          break;
       }
       else if(x > a[i]) // find the largest value smaller than x, 
       {
           if(liVal < a[i])
               liVal = a[i];
       }

System.out.println(liVal);

这篇关于Java 在数组列表中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆