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);
Answer from K Richardson on Stack OverflowIf 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);
In Java, you can get the first and last elements of an array using the following approaches:
1. Using Array Indexing:
To get the first element, you can access it using index 0. To get the last element, you can access it using the index array.length - 1. Here's an example:
int[] array = {1, 2, 3, 4, 5};
int firstElement = array[0];
int lastElement = array[array.length - 1];
System.out.println("First Element: " + firstElement);
System.out.println("Last Element: " + lastElement);
2. Using ArrayList (if the array is converted to ArrayList):
If you have converted the array to an ArrayList, you can use the get() method to access the first and last elements. To get the first element, use arrayList.get(0). To get the last element, use arrayList.get(arrayList.size() - 1). Here's an example:
import java.util.ArrayList;
int[] array = {1, 2, 3, 4, 5};
ArrayList<Integer> arrayList = new ArrayList<>();
// Convert the array to ArrayList
for (int i : array) {
arrayList.add(i);
}
int firstElement = arrayList.get(0);
int lastElement = arrayList.get(arrayList.size() - 1);
System.out.println("First Element: " + firstElement);
System.out.println("Last Element: " + lastElement);
Both approaches allow you to retrieve the first and last elements of an array in Java. Choose the one that best fits your needs and the type of data structure you are working with.
Another way to get the last token/word
String lastToken = sentance.replaceAll(".* ", "");
You only need to split it once, and take the last element.
String sentence = "Any simpler way to get the last element of a Java array?";
String[] tokens = sentence.split(" ");
String lastToken = tokens[tokens.length-1];
It's awkward, but there's really no other way to do it unless you have foreknowledge of the length of the string.
You could use lastIndexOf() method on String
String last = string.substring(string.lastIndexOf('-') + 1);
Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:
String[] bits = one.split("-");
String lastOne = bits[bits.length-1];
Caveat emptor: if the original string is composed of only the separator, for example "-" or "---", bits.length will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8