Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
Answer from user142162 on Stack OverflowArrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
Videos
To go the other way, you need to start the index at the highest value and decrease it for each iteration. Like this:
for (int i = map.length - 1; i >= 0; i--)
for (int j = map[i].length - 1; j >= 0; j--) {
switch (map[i][j]) {
map[i][j] = new Title();
}
}
Note that in both loops, we are starting from the highest index, map.length - 1 in the first and map[i].length in the second, and going down by one for each iteration until we reach the lowest index, 0 for both loops.
With for(int i = 0; i < length; i++), you're starting at the start (0), and going to the end (length).
To go the other way, just reverse everything:
for(int i = length - 1; i >= 0; i--)
Few things to note:
- We have to do
length - 1, or we'll start 1 past the end - We're using
>=to include 0 - We're decrementing
iinstead of incrementing it.
If you need it for a 2D array, just add a second of the above for the second dimension.
One approach would be to reverse the whole list, but this would have O(n) performance with respect to its size. Note that the commonly-used Collections.reverse method actually reverses the original list in place, which may be an undesirable side-effect.
As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.
For example:
Copypublic class Reversed<T> implements Iterable<T> {
private final List<T> original;
public Reversed(List<T> original) {
this.original = original;
}
public Iterator<T> iterator() {
final ListIterator<T> i = original.listIterator(original.size());
return new Iterator<T>() {
public boolean hasNext() { return i.hasPrevious(); }
public T next() { return i.previous(); }
public void remove() { i.remove(); }
};
}
public static <T> Reversed<T> reversed(List<T> original) {
return new Reversed<T>(original);
}
}
And you would use it like:
Copyimport static Reversed.reversed;
...
List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
doSomethingWith(s);
}
Update for Java 21
As per this answer, Java 21 includes an efficient List.reversed() method which does exactly what is requested.
For a list, you could use the Google Guava Library:
Copyfor (String item : Lists.reverse(stringList))
{
// ...
}
Note that Lists.reverse doesn't reverse the whole collection, or do anything like it - it just allows iteration and random access, in the reverse order. This is more efficient than reversing the collection first.
To reverse an arbitrary iterable, you'd have to read it all and then "replay" it backwards.
(If you're not already using it, I'd thoroughly recommend you have a look at the Guava. It's great stuff.)
Try this:
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}
Guava offers Lists#reverse(List) and ImmutableList#reverse(). As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
arrays have no concept of negative indices, if you want to traverse from the last to first then you must START at the LAST index and move to the FIRST.
for(i =3; i>0; i--){
System.out.println(var[i - 1]);
}
You were starting with a negative index which does not exist in arrays. It's also good practice to use array.length instead of an explicit number in case you change the size of the array later on.
public class RevIntArray {
public static void main(String[] args) {
int var[] = new int[] {1,2,3};
for(int i = var.length - 1; i >= 0 ; i--) {
System.out.println(var[i]);
}
}
}
You declared array on integers of 10 elements. And you are iterating from i=0 to i=10 and i=10 to i=0 that's 11 elements. Obviously it's an index out of bounds error.
Change your code to this
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<10 ; i++) { // from 0 to 9
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=9; j>=0; j--){ // from 9 to 0
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}
Remember indices starts from 0.
.
Java uses 0-based array indexes. When you create an Array of size 10 new int[10] it creates 10 integer 'cells' in the array. The indexes are: 0, 1, 2, ...., 8, 9.
Your loop counts to the index which is 1 less than 11, or 10, and that index does not exist.