Search code examples
javaadditionelementarraydeque

ArrayDeque add multiple elements


Im using arraydeque to create list of items and pass them parameters(Items is class)

ArrayDeque<Item> Items= new ArrayDeque<Item>();

But I have problem with java ArrayDeque. Maybe there are ways to add more than one element at once. For example. I want add at the same time TableType and colourOfTable into ArrayDeque.

In c++ I could have done it with this

vector<Item>Items

Items.push_back(Item("CoffeeTable", "brown"));

I want to do the same thing with Java. Instead of creating a new obj for every item, as:

ArrayDeque<Item> Items = new ArrayDeque<Item>();

Item obj = new Item("CoffeTable", "brown"); 
Items.add(obj);

Item obj1 = new Item("DinnerTable", "Black"); 
Items.add(obj1);

But instead of obj I want to add "CoffeTable", "brown" at the same time and with one code line (like in c++ example) into the Items array.

I tried something like that

ArrayDeque<Item> Items= new ArrayDeque<Item>();

Items.add(Items("CoffeTable", "brown")); 

But then got the error while creating create method 'Items(String,String)'


Solution

  • You can simple create the new item in the call of add:

    items.add(new Item("CoffeTable", "brown"));
    

    So you don't need an explicit variable.

    Also note that in Java variable names normally start with a lower case character.