• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList index check  RSS feed

 
Hans Baba
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys; I have a short question for you here.

How could I check if an index is exist in an array list? I mean, I should enter an integer and it should return me a boolean result that saying whether if that entered value is an index or not.

Thanks
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean whether the List has a large enough size to use a particular index? Go through the List interface methods and there is a method which should tell you the current size of the List.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there is not a method with boolean return type which does that.
 
Hans Baba
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
indexOf

int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

Parameters:
o - element to search for

Returns:
the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element

Throws:
ClassCastException - if the type of the specified element is incompatible with this list (optional)
NullPointerException - if the specified element is null and this list does not permit null elements (optional)

------------------------------------------------------------
I know I have to do something with these, but not very clear about it
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have an array or a list of length N, then any index between 0 and N - 1 (inclusive) is a valid index for the array or list.

The indexOf method of interface List is something else. It checks if there is an object in the list that is equal to the object you pass to the method, and if it exists, it gives you the index in the list of the object. That is not the same as what you were asking in your question above.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!