Home > Back-end >  getting error at "temparr.get(newindex) = arr.get(i);" this line in code //getting error i
getting error at "temparr.get(newindex) = arr.get(i);" this line in code //getting error i

Time:03-20

getting error at "temparr.get(newindex) = arr.get(i);" this line in code //getting error in this line as it converting list to array help for this

class Result {
        public static List<Integer> rotateLeft(int d, List<Integer> arr, int n) {
            // Write your code here
            List<Integer> temparr = new ArrayList<Integer>();
            for (int i = 0; i < n; i  ) {
                int newindex = ((i   (n - d)) % n);
                // System.out.println(newindex);
                temparr.get(newindex) = arr.get(i); //getting error in this line as it 
                 converting list to array help for this 
            }
            return temparr;
}
}

CodePudding user response:

First off, you should make sure you are using the right terms. You aren't converting a List into an array, but into an ArrayList. An ArrayList is called that, because it has random access like an array (and actually uses an array internally), but it's not an array.

Your code has two problems: Java (and in fact many programming languages) don't allow you use a method call on the left side of an assignment statement (=).

I'm guessing you want to assign the value of arr.get(i) to the index newindex of temparr (*), so you need to use the .set() method:

temparr.set(newindex, arr.get(i));

However this won't work either, yet. The ArrayList you have created has a size of 0 and thus can't have values assigned to indexes larger than 0. The way you are using the list you'll need to initialize it with n values (for example, 0 or null). This could be done, for example, with Collections.nCopies():

List<Integer> temparr = new ArrayList<Integer>(Collections.nCopies(n, 0));

(*) NB: "temparr" is a bad variable name. It's not an array, and all variables are "temp"orary. Use names that explicitly describe the content or purpose. In this case I'd suggest rotatedList.

  • Related