-3
public LibraryClass(int x) {
    bookShelf = new TextBook[x];
    for(int i=0;i<x;i++){
        bookShelf[i] = new TextBook("textbook" + i, 5);
    }
    nextBook = x - 1;  
    }

So this is my code, and whatever input we give the int x, for example 5, the max index would be 4. i could easily yes put a pointer on this position, but is there any other code which gives me the highest index number (NOT the highest element) to me?

anony
  • 79
  • 1
  • 2
  • 10
  • Since you surely mean the "highest index number with an `TextBook` instance" you should write that in your question. Btw, prefer a `List` instead. – Tom Nov 03 '15 at 12:35

3 Answers3

3
int highest =  bookShelf.length -1;

Will give the result which is the highest index of array.

The reason for doing -1 is array indices starts from zero. Hence the 5 indices array length will be 6.

It seems you are looking for next and previous navigations, hence you might want to look at the data structure LinkedList

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

The highest index of an array is always array.length - 1 (or bookShelf.length - 1 in your specific example).

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Just to repeat what others have said, use

array.length - 1

to get the highest index in the array. Or, given your example,

x - 1

To expand on what others have said, see this SO question for more info on arrays and of course the documentation for more functions on arrays.

Community
  • 1
  • 1
Arc676
  • 4,445
  • 3
  • 28
  • 44