learning2code
learning2code

Reputation: 31

How to perform Arithmetic with ArrayList values

I'm a beginner at using ArrayList and I want to add a number to a value stored in an element. Basically I want to do arlist(0) += number. here is my code (I've only pasted the relevant parts).

ArrayList<Integer> snakex = new ArrayList<Integer>();
snakex.add(630);

I'm not sure how to go on from here. I've tried:

snakex.get(0) += 5;

Doing this I get the error "The left-hand side of an assignment must be a variable".

How would I be able to change the value of snakex(0) from 630 to 635?.

Thank you !

Upvotes: 1

Views: 704

Answers (4)

Md. Sajedul Karim
Md. Sajedul Karim

Reputation: 7045

Here I am giving some example for arrayList:

ArrayList<Integer> snakex = new ArrayList<Integer>();

        snakex.add(630);
        snakex.add(640);
        snakex.add(650);
        snakex.add(660);

        for (int index = 0; index < snakex.size(); index++) {
            Integer item=snakex.get(index);//getting item for position
            snakex.set(index,(item+5)); // It is adding 5 with each item and storing tht position
        }

        // print each item using for each
        for (Integer item:snakex) {
            System.out.println(item+" ");
        }

        // delete item which value is 640
        for (int index = 0; index < snakex.size(); index++) {
            Integer item=snakex.get(index);//getting item for position

            if(item==640){
                snakex.remove(item);
            }
        }

For more info please visit here

Hope this will help you.

Thanks :)

Upvotes: 0

Zain Arshad
Zain Arshad

Reputation: 1907

You are using the ArrayList.get() method which is returning an integer and when you add that value to an integer it gives error, which is rightly so. Now you have to use get() method in conjunction with set() method like this:

//index to change, so in future you don't need to 
//change whole code just change value of 'i'
int i = 0; 
snakex.set(i, snakex.get(i)+5);  //first calls the 'get()' method and then sets that value

For more on ArrayList click here

Upvotes: 1

FailingCoder
FailingCoder

Reputation: 767

You can use the set() method of java.util.ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, first is the index of an element you want to replace and second is the new value you want to insert.

i.e.

snakex.set(0, snakex.get(0)+5)

Upvotes: 0

gmanrocks
gmanrocks

Reputation: 281

What you are basically doing is:

snakex.get(0) += 5 -> 630 += 5 -> 635; 

It does not know what to do from there. Instead do:

snakex.set(0, snakex.get(0) + 5)

The set method is defined by set(int index, Object o) . The get(int index) gets the value at the specified index. The set(int index, Object o) sets the value at the specified index to the object.

Upvotes: 0

Related Questions