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?
// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};
// First position
double firstNum = array_doubles[0]; // 2.5
// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6
This is the same in any array.
I think there is only one intuitive solution and it is:
int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);
Output:
First: 1
Last: 5
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]
This is the given array.
int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};
// If you want print the last element in the array.
int lastNumerOfArray= myIntegerNumbers[9];
Log.i("MyTag", lastNumerOfArray + "");
// If you want to print the number of element in the array.
Log.i("MyTag", "The number of elements inside" +
"the array " +myIntegerNumbers.length);
// Second method to print the last element inside the array.
Log.i("MyTag", "The last elements inside " +
"the array " + myIntegerNumbers[myIntegerNumbers.length-1]);
Check this
double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first
Source: Stackoverflow.com