简体   繁体   English

如何在java中获取数组中的第一个和最后一个元素?

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

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?我该怎么做?

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); 

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]
// 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.这在任何数组中都是一样的。

Check this检查这个

double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first

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

getting first and last element in an array in java在java中获取数组中的第一个和最后一个元素

double[] numbers = {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,};


double firstNumber= numbers[0];

double lastNumber = numbers[numbers.length-1];

System.out.println("firstNum = "+ firstNumber);

System.out.println("lastNum = "+ lastNumber);

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM