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
if you have this list and search 26, it will output the first element. because the first element is <= than the value being search.
but current output is
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);
}
}
ArrayListto keep it sorted?