简体   繁体   中英

How to check in an array list if an item is immediately followed by another - Java

I am currently stuck on a part of my project.

I cannot figure out how to (in Java) to check whether in an existing array list, an item is followed immediately by another item. So, for example, if x is followed by y in the array list: a, b, c, x, y, z.

It needs to be a recurring thing as there can be multiple same values in the list, so multiple x and y items for example.

Can someone help me with coming up with the code for this? It needs to be a method that returns true or false.

Thank you.

Just loop:

for (int i = 0; i < list.size() - 1; i++)

-1... because the LAST element couldn't possibly match, as it is not followed by anything.

You can retrieve an item at an index as list.get(i) , and of course the element that follows it with list.get(i + 1) .

Surely you can put it together with this information (I'm loathe to give more; this feels like homework).

If (list.indexOf(item1) == list.indexOf(item2) -1) { return true ; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM