Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to return the only element in an ArrayList

Tags:

java

arraylist

I am working on a Robot Maze where the robot finds the target without crashing into walls. I have commented my code thoroughly so hopefully it'll be understandable.

At the dead end and corridor, there will be only one passage in the passageDirections ArrayList. How do I return this one and only direction?

Any help is appreciated :)

PS: I am a beginner programmer, still learning so explain your answer as if you were to explain it to a three year old :)

like image 364
codeav3 Avatar asked Mar 03 '26 09:03

codeav3


2 Answers

You can use passageDirections.get(0), which will return the first element in the list. Since (I hope that) you guarantee there is a single element in the list, that solves your issue.

https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)

like image 110
João Neto Avatar answered Mar 04 '26 21:03

João Neto


You should check the size before calling to prevent IndexOutOfBoundsException

if (passageDirections.size() > 0)
  passageDirections.get(0)
like image 28
display name Avatar answered Mar 04 '26 23:03

display name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!