If I have an array of doubles:
[10.2, 20, 11.1, 21, 31, 12, 22.5, 32, 42, 13.6, 23, 32, 43.3, 53, 14, 24, 34, 44, 54, 64, 15.1, 25, 35, 45, 55, 65.3, 75.4, 16, 26, 17.5,]
and I want to get the first element and last element so that
firstNum = 10.2 lastNum = 17.5
how would I do this?
To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.
The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1) , so you would use myArrayList. get(myArrayList. size()-1) to retrieve the last element.
To get the first element of a ArrayList, we can use the list. get() method by passing 0 as an argument. 0 is refers to first element index.
Overview. The size() in Java is a predefined method of the ArrayList class. It is used to calculate the number of objects in an ArrayList. It Does not take any input parameter, and whenever the ArrayList calls this function, it returns an integer representing the number of elements of ArrayList.
If you have a double array named numbers
, you can use:
firstNum = numbers[0]; lastNum = numbers[numbers.length-1];
or with ArrayList
firstNum = numbers.get(0); lastNum = numbers.get(numbers.size() - 1);
Getting first and last elements in an array in Java
int[] a = new int[]{1, 8, 5, 9, 4}; First Element: a[0] Last Element: a[a.length-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With