Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first and last element in an array in java?

Tags:

java

arrays

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?

like image 577
Jotaro Avatar asked Oct 04 '16 19:10

Jotaro


People also ask

How do you find the last and first element in an array?

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.

How do you call the last stored variable in an 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.

How do I find the first element of an ArrayList?

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.

What does .size do in Java?

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.


2 Answers

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);  
like image 194
K Richardson Avatar answered Sep 28 '22 02:09

K Richardson


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] 
like image 37
Yagmur SAHIN Avatar answered Sep 28 '22 03:09

Yagmur SAHIN