# Thread: Checking for two consecutive elements in Collection

1. Originally Posted by Junky
Java Code:
`return x.indexOf(i+1);`
Lets say that 4 is located at position 9 and therefore 8 is located at position 10, which means i equals 9. The above line is trying to find the index of the number 10 (9 + 1) in your list. Which may or may not be present but most assuredly it is not what you should be doing.

Also why are you hard coding the values 4 & 8. You should write this so it can search for any pair of values.
Hello Junky.

I have just gone through it on pen and paper, and it made sense to me ! (Did you notice the OR { || } operator in my code?) also I actually went ahead and tried it with my "Play" program, and it worked ! (for the return problem I was having, I just made it return -1) Here's the full code (slight changes exist).

Java Code:
```import java.util.ArrayList;

public class JavaPlay {

private ArrayList<String> x;
private ArrayList<String> y;

public JavaPlay()
{
x = new ArrayList<String>();
y = new ArrayList<String>();
}

public void fillArrayX()
{
}

/*
* Checks if two consecutive elements exist in the ArrayList
* and returns the index of the last of the two.
* @return Integer
*/
public int findThem()
{
//ArrayList<Integer> z = new ArrayList<Integer>();
int size = x.size();
for(int i = 0; i < size ; i++)
{
if(x.get(i).equals("s2") || x.get(i).equals("s3"))
{
if(x.get(i+1).equals("s3") || x.get(i+1).equals("s2"))
{
return x.indexOf(x.get(i+1));
}
}
}

return -1;
}

/*
* Inserts the two consecutive elements right after where
* they existed before.
* @return Integer
*/
public void reInsertThem()
{
String u = x.get(findThem() -1);
String z = x.get(findThem());

}

public void printArrayX()
{
System.out.println("Array X:" + x);
}
}```
And here is my Main.java class:

Java Code:
```public class Main {

public static void main(String[] args) {

JavaPlay z = new JavaPlay();
z.fillArrayX();
z.printArrayX();
z.findThem();
z.reInsertThem();
z.printArrayX();
}

}```
When I run this little play program, I get the following output in the console.

Array X:[s0, s1, s2, s3, s4]
Array X:[s0, s1, s2, s3, s2, s3, s4]
Which is what I was expecting ! Now >> time to move onto the real thing.

Thanks

2. Java Code:
`return x.indexOf(x.get(i+1));`
A lot of wasted effort. The above line can be simplified to
Java Code:
`return i+1;`

3. Another thing I just thought of: what happens if one of the objects you are searching for is the last element? i + 1 will throw and IOOBE.

4. Senior Member
Join Date
Jun 2008
Posts
339
Rep Power
6
Coming in late on the OP - ArrayDeque has a forward and an reverse iterator that could help find consecutive elements. Alternatively, it has a toArray() method that returns an array that can be wrapped in a List using Arrays.asList(..). So you can very simply have random access via an array or a List.

Page 2 of 2 First 12