0

I want to be able to decrease a value in an ArrayList to simulate an object being removed from a pile. However I cannot do this with ArrayList(String)

The example below is what i've attempted.

ItemArray.get(pressedItem + 1) = (ItemArray.get(pressedItem + 1)) - 1

Is there a way to get values in an ArrayList into a more manipulatable state?

EDIT:

Just to point out that my ArrayList is ArrayList(String) at the moment

0

2 Answers 2

3

You need to use List#set() to mutate the list.

List<Integer> items = new ArrayList<Integer>();
// later...
int position = pressedItem + 1;
items.set(position, items.get(position) - 1);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick response man but ItemArray.get(position) - 1 returns an error The operator - is undefined for the argument type(s) String, int
@Jack That means your list is set to contain Strings. Java is strongly typed, it's not gonna magically turn a String into a numeric value. Either specify your list as containing the Integer type or convert the String to an Integer.
Ah brilliant, that's perfect thank you =) Could you put something about converting to an integer in your answer? Thank you.
Use the right data type for your data; store a list of integers, not strings.
2

ArrayList is a class. Assuming ItemArray is an instance of that class (please start variables with a lower-case letter, btw), you'll need to use it through method calls. In your case, set. Like so:

itemArray.set(pressedItem + 1, itemArray.get(pressedItem + 1) - 1)

Mind that the above will only work exactly like that if you declared your ArrayList as containing Integers or some other numeric type, so Java can do the conversion stuff for you:

List<Integer> itemArray = new ArrayList<Integer>();

2 Comments

Doesn't look like I can declare my ArrayList with <Integer> because i'm populating it with the contents of a CSV file :/ It is currently <String>
@Jack Then you'll either have to a) convert while populating the list or b) store Strings and convert when they're used. a) is preferrable since it catches incorrect input sooner and makes later processing easier.

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.