Simple question, but everytime I google it there are only examples using an ArrayList, and list.indexOf(3), doesn't work on int[] nums = new int[10]. Soo im a little confused.
Asked
Active
Viewed 439 times
-1
-
And, the list consists of 10 elements. I was just writing int[] to show it's not an arraylist – memelord23 Dec 16 '15 at 02:38
-
What's the question? – Maria Ines Parnisari Dec 16 '15 at 02:39
-
Iteration is `O(n)`, for a `List` or an `int[]`. Which do you have? Oh, and `Arrays.asList(nums).indexOf(3)` works if `nums` is an `Integer[]`. – Elliott Frisch Dec 16 '15 at 02:39
-
nums[***you're index here ***] – Mike Dec 16 '15 at 02:40
-
@mike The website you gave me tells me to use indexOf(object o), but when I type it on my ide, it says. Cannot invoke indexOf(int) on array type int[] – memelord23 Dec 16 '15 at 02:42
-
Yeah sorry about that. That site was meant for lists, but you instantiated an array which is different. – Mike Dec 16 '15 at 02:50
2 Answers
4
Here's the real problem. You appear to think that
int[] nums = new int[10]
is defining a List
or a list. It isn't. It is an array. The words "list" and "array" are NOT synonymous in the context of Java. So when you Google for "finding an index of an element in a list" ... you don't get any useful hits.
If you use the >>correct<< terms when searching (Google, SO search, anything) you are far more likely to get useful search results.
For example:
FWIW, if you want a (real) list of integers in Java you declare it like this:
List<Integer> nums = new ArrayList<>();
Notes
- You have to use
Integer
as the type parameter, notint
. - You don't need to provide
10
as a parameter. And if you do, it is a hint that tells theArrayList
what the initial capacity of the list should be. (For an array it is the actual size ... and it can't be changed).
-
1ohh yea I thought it created a list with 10 indexes. Lame, alright I better find the difference between list and array thanks. – memelord23 Dec 16 '15 at 02:49
0
If you want to use indexOf(3) on an array you could create a List from it
ArrayList<Integer> myInts = new ArrayList<Integer>(Arrays.asList(array))
and then you can use
myInts.indexOf(3)

Lazy Senior
- 171
- 1
- 8