0

I'm trying to retrieve the item at the specified index in an array as shown in the body of the forloop.

public int arrayCount9(int[] nums) {
    int count = 0;

    for (int i = 0; i < nums.length; i ++) {
        if (Array.get(nums, i) == 9) {
            count ++;
        }
    }    
    return count;
}

However, the correct code in this problem is actually this:

public int arrayCount9(int[] nums) {
    int count = 0;

    for (int i = 0; i < nums.length; i ++) {
        if (nums[i] == 9) {
            count ++;
        }
    }
    return count;
}

Is there a difference between Array.get(nums, i) == 9) and (nums[i] == 9)? The documentation for get(Object array,int index) seems suitable for this problem. In addition, I've actually never encountered (nums[i] == 9) before so if you could explain that code as well, much appreciated!

6
  • 1
    I didn't even know this class Array exists. What the heck is the purpose of it?
    – akuzminykh
    Commented Jun 19, 2020 at 22:26
  • 1
    @akuzminykh To dynamically create arrays from Class objects? I have to agree that most of the methods seem useless
    – user
    Commented Jun 19, 2020 at 22:28
  • 1
    The get method works with arrays of Objects. Use getInt instead if you have to. However, I don't understand why you simply can't use the second approach with nums[i]
    – user
    Commented Jun 19, 2020 at 22:31
  • I will use the second approach as it's the only one working. Just wanted to know the difference between the two. Thanks for your help guys! Commented Jun 19, 2020 at 22:40
  • Array is the class you'd use when working with the Reflection API and don't want to cast.
    – Felix
    Commented Jun 19, 2020 at 22:52

1 Answer 1

2

As far as I can tell from the documentation, the most important difference between the two is that Array.get(myArray, myIndex) will return a raw Object, whereas myArray[myIndex] will return a value of the type that myArray stores.

For example, if you have an array of Strings named myStringArray, Array.get(myStringArray, 4) will give you a nondescript Object value, whereas myStringArray[4] will give you a String value.

In general, people tend to use the myArray[myIndex] syntax unless they have a compelling reason not to. It essentially means "get the item in the array named myArray at index myIndex."

1
  • 2
    Relatively new to java so unsure what's the conventions are but I'll be using myArray[myIndex] from now on. It seems more intuitive anyways. thanks a bunch EKW. Commented Jun 19, 2020 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.