0

I'm writing a method that takes an ArrayList and uses the element at a certain index in a different location , yet when I use the .get(int) method in the code, I get an error.

static void linreg(ArrayList<Integer> x[], ArrayList<Integer> y[]) {

        double sum_x = 0, sum_y = 0, int n = 15;
        
        for (int i = 0; i < n; i++) {

          sum_x += x.get(i); - Cannot invoke get(int) on the array type ArrayList<Integer>[]
          sum_y += y.get(i); - Cannot invoke get(int) on the array type ArrayList<Integer>[] 

Is there a way to fix this? Thanks

3
  • What are you trying to do? Commented Aug 25, 2021 at 0:24
  • 1
    Delete both []. They don't do what you think they do. Commented Aug 25, 2021 at 0:39
  • Side note: it is usually much better to do a List<List<Integer>> construct than to mix arrays with lists as you're trying to do. Commented Aug 25, 2021 at 1:04

2 Answers 2

2

The parameters x and y are arrays. Arrays in java don't have a get method. That's why you get the error. You don't even need them as arrays. You just need them as lists which do have get method.

static void linreg(List<Integer> x, List<Integer> y) {

        double sum_x = 0, sum_y = 0, int n = 15;
        
        for (int i = 0; i < n; i++) {

          sum_x += x.get(i); 
          sum_y += y.get(i);
        }
        System.out.println(sum_x);
        System.out.println(sum_y);
 }
Sign up to request clarification or add additional context in comments.

Comments

2

x is not of type ArrayList<Integer>, it is of type ArrayList<Integer>[]. (Note that it is not recommended to use this syntax exactly because of the confusion you had.) Perhaps you didn't mean to have both an array and a list.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.