How do i check if and index of an ArrayDeque is empty?

1.8k Views Asked by At

I am trying to add some strings in an ArrayDeque but first I have to check if its already full that index. How i can do it?

I have this:

 public void processarEntrada(String n){

    for ( int i = 0; i <= 3; i++){
        planta.add(n);

Each index has to be empty before adding anything

3

There are 3 best solutions below

0
On

I've had a bit trouble to fully understand the question. What I understood is that you wish to add it into ArrayDeque if only if the array does not contain the string already.

Take a look into Java documentation: public boolean contains(Object o)

Returns true if this deque contains the specified element. More formally, returns true if and only if this deque contains at least one element e such that o.equals(e).

So I would check if it is in the ArrayDeque and then add it.

if(! planta.contains(theString)) planta.offer(theString);

0
On

Here is a good example for you.

import java.util.ArrayDeque;
import java.util.Iterator;

public class ArrayDequeTest {
    public static void main(String... args){

        ArrayDeque<String> aq= new ArrayDeque<String>();
        aq.add("A");
        aq.add("B");
        aq.add("C");

        //offerFirst-adds elements at the front of the ArrayDeque 
        aq.offerFirst("D");

        //offerLast inserts the element at the last of ArrayDeque 
        aq.offerLast("E");

        Iterator<String> itr= aq.iterator();
        while(itr.hasNext()){ 
            System.out.println(itr.next());
        }

    }
0
On

ArrayDeque Java doc

Array deques have no capacity restrictions; they grow as necessary to support usage.

add(E e)
Inserts the specified element at the end of this deque.

The add method will create a new index and add elements that index.

Each index has to be empty before adding anything

No additional work is required to implement this.