Domanda

I'm little bit confused when do I really need to use that length-1. I know that is when we don't want to have out of bound error. For instance I wrote this simple array:

    int [] oldArray = {1, 5, 6, 10, 25, 17};

    for(int i = 0; i < oldArray.length; i++){

It does not give me any error. Any examples when -1 is actually useful? Thank you in advance.

È stato utile?

Soluzione

You want to use oldArray.length usually in a for loop call, because as in your example,

for(int i = 0; i < oldArray.length; i++) {
    //Executes from i = 0 to i = oldArray.length - 1 (inclusive)
}

Notice how i goes from 0 up until oldArray.length - 1, but stops exacty at oldArray.length (and doesn't execute). Since arrays start at position 0 instead of 1, old.Array.length is a perfect fit for the number that i should stop at. If arrays started at position 1 instead, for loops would look something like this:

for(int i = 1; i <= oldArray.length; i++) {
    //Executes from i = 1 to i = oldArray.length (inclusive)
}

oldArray.length - 1 is usually to access the last element:

int[] oldArray = {1,2,3,4,5};
int lastElement = oldArray.length - 1; // 4
oldArray[lastElement] // returns last element, 5

Although this is usually when you would use length - 1 vs length, there are many other cases where you would also want one over the other, and thus there is no real specific answer. But don't worry, keep coding, you'll get this hang of this soon ;)

Altri suggerimenti

for(int i = 0; i < oldArray.length; i++)

is equivalent to

for(int i = 0; i <= oldArray.length - 1; i++)

Loops and array utility methods can use array.length to mean "up to the last element".

The only place I can think of for using array.length - 1 is when accessing the last element, eg to find largest number in an array:

int[] array;
Arrays.sort(array);
int largest = array[array.length - 1];

This completely depends on what you want to do. In an array you have a collection of things. If you were shown this array [1,2,3,4] say, in elementary school and someone asked you how many things are in there you would say four. You would count starting from one, which is completely reasonable. If someone asked you what the third thing in that array was, you'd point to the 3. Awesome! Except, now that you're coding, you know that arrays start at zero. So even though there are still four things in that array, their names have changed. Now 1's name is zero, 2's name is one, 3's name is two, and 4's name is three. So when you're using a loop and you just want the loop to go through all the things and that's it (like if you're searching through an array), you can use .length and it'll just run through. If you want to access the number 4 in the array specifically, though, 4's name is no longer 4 - it's 3! So you use length-1 because when it comes to indexes, we're using the new name given to the physical thing.

int [] oldArray = {1, 5, 6, 10, 25, 17};

for(int i = 0; i < oldArray.length; i++){

=>

int [] oldArray = {1, 5, 6, 10, 25, 17};

for(int i = 0; i <= oldArray.length - 1; i++){

So basically, you want to use oldArray.length - 1 when you need to access the last element.

There is no specific answer for your question. It depends. one point is when you want to index the last element of an array

int lastElement = oldArray[oldArray.length-1];

Simply put, although your array has 6 elements, the indexing of the array begins at 0. That means that the index of the first element is 0, the second element 1, ... and the 6th element 5. Therefore, if you try to access oldArray[6], you will get an error. In the loop you demonstrate, this is never the case:

for(int i = 0; i < oldArray.length; i++)

oldArray.length returns 6. The highest value of i reached in the loop is 5, since the loop will break when the value of i becomes 6. This is why there are no errors. So to answer your question directly, oldArray[oldArray.length - 1] will return the last element in the array.

you can write as below as well:

for(int i = 0; i <= oldArray.length-1; i++){

oldArray.length-1 is needed when you want that particular element i.e. final element from array.

i.e. oldArray[oldArray.length-1]

It is use when you want to get the last index number of the array. Seens the computer dosent know how long your array is it gets the indication by using -1. Seens 0 is the start then -1 is the end of the array.

I use this when i want to sort numbers just like the example that Bohemian wrote. Take a look at bubble sort algorithem

{
   int[] arr= new int[5]{23,2,3,34,6}; // unsorted data set
   bubblesort(arr,5); // sorting process using bubble sort
   int i;
  for(i=0;i<5;i++)
      Console.Write(arr[i]); //after sorting
  Console.ReadLine();

}

//bubble sort

static void bubblesort(int[] dataset, int n){
   int i,j;
   for(i=0;i<n;i++)
     for(j=n-1;j>i;j--)
        if(dataset[j]<dataset[j-1])
       {
          int temp=dataset[j];
          dataset[j]=dataset[j-1];
          dataset[j-1]=temp;
        }

     }
   }
}
for (int i = 0; i < array.length; i++) {
    // this will loop throw the entire array
 }

if you want to access an element from array, you need to use array.length-1

 lastElement = array.length -1;

The main rule is to remember is the Array is starts with 0. While .length is returns the actual number of array, so length do not count or start with 0

So, as per your example:

  int [] oldArray = {1, 5, 6, 10, 25, 17};

Here in your example below

 for(int i = 0; i < oldArray.length; i++){}

The i starts with 0 and loop continue till i value as 5 as you are using < only.

If you try to use <= it will fail again, as you try to assess 7th(0-6) element which is not present.

Now take a another example as below, where we try to reverse a string:

    String name="automation";
    
    System.out.println(name.length());
    
    for(int i=name.length()-1;i>=0;i--) {
        System.out.print(name.charAt(i));
    }

Output:

10

noitamotua

Now in above example if you don't use -1 the value 10 will be pass inside the loop, as the length return 10 as per length of string but for array 10th element not present as array starts with 0 so it require till 9th place only as per above example , if you pass 10 it will throw error as 10th position is not present for it, thats why we need to use -1 at least for decrements(i--) order for sure

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top