如何在java中获取数组中的第一个和最后一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39860739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get first and last element in an array in java?
提问by Jotaro
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?
我该怎么做?
回答by K Richardson
If you have a double array named numbers, you can use:
如果您有一个名为 的双数组 numbers,则可以使用:
firstNum = numbers[0];
lastNum = numbers[numbers.length-1];
or with ArrayList
或与 ArrayList
firstNum = numbers.get(0);
lastNum = numbers.get(numbers.size() - 1);
回答by XavCo7
// 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.
这在任何数组中都是一样的。
回答by fsalazar_sch
Check this
检查这个
double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first
回答by Wigglepee
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
回答by Yagmur SAHIN
Getting first and last elements in an array in Java
在Java中获取数组中的第一个和最后一个元素
int[] a = new int[]{1, 8, 5, 9, 4};
First Element: a[0]
Last Element: a[a.length-1]
回答by TEJVEER SINGH
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]);

