Checking for two consecutive elements in Collection

Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last
• 06-30-2011, 02:37 AM
Ciwan
Checking for two consecutive elements in Collection
Greetings knowledgeable Java people.

I've hit a wall again, and I'm afraid I'll sink deeper into your debts. :(doh):

please consider with me, the following collection. Let's say it is of type ArrayList (I don't think it matters too much what type of collection it is).

http://i54.tinypic.com/ok7eie.gif

What would be the best approach to take if I wanted to check the ArrayList and see if the two numbers [4] and [8] ever come neighbours of each other ? and if they do, add the couple into the ArrayList once more (right after their original index), making the final list as follows:

[1 , 2 , 4 , 8 , 4 , 8 , 16]

I've thought hard about it, but my programming logic is still minute compared to yours. And couldn't really come up with anything of use.

I would greatly appreciate any help.

Thank You.
• 06-30-2011, 02:41 AM
Junky
Break it down into smaller steps. Try finding if the first search target is present in the list. Once you have got that working then see if the next element is the other search target. Get that working. If you have found both targets then add new elements in the list.
• 07-01-2011, 12:18 AM
Ciwan
Hello Junky, Thanks for the reply.

Quote:

Try finding if the first search target is present in the list. Once you have got that working then see if the next element is the other search target.
Let's say I use the code below to find element 4. How can I then find out that, its neighbour on either side is element 8.

Code:

```public void findThem() {         for(Integer i : x)         {                 if(i == 4)                 {                         // gets here if 4 exists.                 }         } }```
I've looked through the API and there isn't any method that would give you the neighbour of a particular element. !

Thanks
• 07-01-2011, 12:25 AM
Norm
Quote:

looked through the API and there isn't any method that would give you the neighbour of a particular element.
What data type is x? What methods does it have?
• 07-01-2011, 12:33 AM
Ciwan
Ooops sorry forgot to mention. :frusty:

Code:

`private ArrayDeque<Integer> x;`
It has the following in it:

[1 , 2 , 4 , 8 , 16]

Thanks Norm.
• 07-01-2011, 12:41 AM
Norm
Why are you using an ArrayDeque if you need to look at the interior contents of the collection?
• 07-01-2011, 12:54 AM
Ciwan
Because for certain parts of my logic for this project, an ArrayDeque is exactly what is needed.

What do you suggest I use for this part of my logic ? a regular ArrayList ? or do you have something better ? I'm guessing if it is a collection, it will have the .addAll(collection E) method that you taught me to use yesterday. So it shouldn't be too hard moving the stuff from the ArrayDeque to whatever Collection type you think is best.

Thanks
• 07-01-2011, 12:58 AM
Norm
Use the tool that fits. If you need to look at the interior of the collection, then ArrayDeque doesn't work. At least not easily.
• 07-01-2011, 01:07 AM
Ciwan
Yep I fully got you. In that case, I can transfer the stuff from the ArrayDeque to a { ...?... } then when I've done my business there, I can transfer back to ArrayDeque.

But what is this "tool that fits" that you mentioned ? I Googled "Checking Interior of Collection Java" and nothing useful came up. :=(:
• 07-01-2011, 01:07 AM
Junky
As Norm said Queues are not designed for random access. Like Stacks they are used when you only need to access the first element, just like in real life. Nobody is pleased when they are at the fron of a queue and someone behind them gets served first.

If you use a List then there is a get method. You iterate over your List using a counter. When you have found the first element then the next element is get(counter + 1).
• 07-01-2011, 01:11 AM
sunde887
Taking a snapshot of the array deque and making it an array list with the addAll method may be helpful. From there it should be fairly simple with a normal for loop rather than the enhanced for loop.

Edit: too slow
• 07-01-2011, 01:14 AM
Ciwan
Thanks Junky.

I've just looked at the List class in the API and it doesn't say that List is a type of collection ! Which (correct me if I'm wrong) means that I can not do list.addAll(x) where x is an ArrayDeque right ?

An ArrayList is a type of collection, and so the addAll() method would work with that ? Wouldn't it be better to use an ArrayList ?

Thanks
• 07-01-2011, 01:16 AM
sunde887
List (Java Platform SE 6)

Yes it is a collection.
• 07-01-2011, 01:18 AM
Junky
List is indeed a Collection and it has an addAll method. Note that List is an interface so you would need to use one of its implementing classes.
• 07-01-2011, 01:39 AM
Ciwan
Cool Thank You. [ArrayList] is one of those classes implementing [List].

OK so I've had ago, I've broken it down like Junky suggested in his second post.

Code:

```/*         * Checks if two consecutive elements exist in the ArrayList         * and returns the index of the last of the two.         * @return Integer         */         public Integer findThem()         {                 //ArrayList<Integer> z = new ArrayList<Integer>();                 int size = x.size();                 for(int i = 0; i < size ; i++)                 {                         if(x.get(i) == 4 || x.get(i) == 8)                         {                                 if(x.get(i+1) == 8 || x.get(i+1) == 4)                                 {                                         return x.indexOf(i+1);                                 }                         }                 }         }                 /*         * Inserts the two consecutive elements right after where         * they existed before.         * @return Integer         */         public void reInsertThem()         {                 Integer u = x.get(findThem() -1);                 Integer z = x.get(findThem());                                 x.add(u, (findThem() -1));                 x.add(z, findThem());                        }```
There is a problem with the findThem() method. It says not all paths return an Integer type value. Which is correct ! Because of the if statements.

But I do not really want to return anything if the condition is not matched ! How do I get over this ? I tried

Code:

`else { return null; }`
Tried the above for both if statements, but it didn't work. :s:
• 07-01-2011, 02:02 AM
Junky
Quote:

Originally Posted by Ciwan
but it didn't work.

In that case try something else. In future if you want more precise help then provide more precise information.

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.
• 07-01-2011, 02:35 AM
Norm
Code:

```if(x.get(i) == 4 || x.get(i) == 8)                        {     if(x.get(i+1) == 8 || x.get(i+1) == 4)```
How many situations/values will these two if statements be true for?
• 07-01-2011, 02:49 AM
Ciwan
Quote:

Originally Posted by Junky
In that case try something else.

I would if I knew what else to try :(-:

Quote:

Originally Posted by Junky
In future if you want more precise help then provide more precise information.

I thought one of my good forum qualities was providing precise information (use of images, clear explanations and so on) :(sweat): Sure, sometimes I'd forget something really important, but then Norm would point it out and I'd place it straight away :(nod): So that I can improve myself for next time, where do you feel I needed to provide more precise information ? :(think):

Quote:

Originally Posted by Junky
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.

I'll go and get a piece of paper and a pen. I'll need to work this out slowly. I've skimmed over it again, and couldn't find anything wrong .. I may be missing something. Will let you know what I find out after the pen & paper. :(y):

Quote:

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

Norm taught me to write small "play" programs at first just to make sure things are doing what I am expecting them to do. If all is OK, then I move it over to the real thing.

Quote:

Originally Posted by Norm
How many situations/values will these two if statements be true for?

Just one, cause my collections won't have duplicates. I will be intentionally introducing the duplicates myself.
• 07-01-2011, 02:55 AM
Junky
Quote:

Originally Posted by Ciwan
So that I can improve myself for next time, where do you feel I needed to provide more precise information.

You need to provide more details than "it didn't work". A gazillion things could have gone wrong. How are we supposed to magically know what went wrong without more details from you. Do you get errors or incorrect behaviour? Try and narrow the problem down to a single line then highligh which line it is. That saves us having to read through a ton of code to track it down. The easier you make it for us the easier and quicker we can provide help.
• 07-01-2011, 03:08 AM
Ciwan
Quote:

Originally Posted by Junky
You need to provide more details than "it didn't work". A gazillion things could have gone wrong. How are we supposed to magically know what went wrong without more details from you. Do you get errors or incorrect behaviour? Try and narrow the problem down to a single line then highligh which line it is. That saves us having to read through a ton of code to track it down. The easier you make it for us the easier and quicker we can provide help.

Awesome thanks for that. Right let me try again, the code wouldn't compile :(nod):

Code:

```public Integer findThem() {         //ArrayList<Integer> z = new ArrayList<Integer>();         int size = x.size();         for(int i = 0; i < size ; i++)         {                 [B]if(x.get(i) == 4 || x.get(i) == 8)[/B]                 {                         [B]if(x.get(i+1) == 8 || x.get(i+1) == 4)[/B]                         {                                 return x.indexOf(i+1);                         }                 }         } }```
I have made bold the lines causing the error (there are 2). The method is set to return an Integer. I have two if statements, if the conditions for these is not meant, I do not want to return anything. So I did the following:

Code:

```public Integer findThem() {         //ArrayList<Integer> z = new ArrayList<Integer>();         int size = x.size();         for(int i = 0; i < size ; i++)         {                 [B]if(x.get(i) == 4 || x.get(i) == 8)[/B]                 {                         [B]if(x.get(i+1) == 8 || x.get(i+1) == 4)[/B]                         {                                 return x.indexOf(i+1);                         } else { return null; }                 } else {return null; }         } }```
But that again gave the same error. The error saying:

Quote:

Not all paths return an Integer.
I hope that's better. :(blush):
Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last