ArrayDeque adds several elements

Im using arraydeque to create a list of elements and pass their parameters (Elements are classes)

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

But I have a problem with java ArrayDeque. Perhaps there are ways to add multiple items at once. For instance. I want to add at the same time TableType and colourOfTable to ArrayDeque.

In C ++, I could do this with this

 vector<Item>Items Items.push_back(Item("CoffeeTable", "brown")); 

I want to do the same with Java. Instead of creating a new object for each element, like:

 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 line of code (for example, in the C ++ example) to the Items array.

I tried something like this

 ArrayDeque<Item> Items= new ArrayDeque<Item>(); Items.add(Items("CoffeTable", "brown")); 

But then an error occurred while creating the create method "Items (String, String)"

+6
source share
3 answers

You can simply create a new element in the add call:

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

Therefore, you do not need an explicit variable.

Also note that in variable names, Java usually starts with a lowercase character.

+2
source

You will need to create a new object to save these 2 values. You can do it:

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

Everything you come up with will be syntactic sugar for the above

For example: you can add a static method to your class:

 public static Item item(String k1, String k2) { return new Item(k1, k2); } 

And use it later:

 Items.add(item("CoffeTable", "Brown")); 
+2
source

Here is a solution that will probably work. You can add a function to your itemAdd () class as follows:

 class Samp { public static void main(String args[]){ //code..... ArrayDeque<Item> Items= new ArrayDeque<Item>(); Items.add(itemAdd("CoffeeTable", "brown")); //rest of code.... } public static Item itemAdd(String tableType,String colourOfTable){ return new Item(tableType,colourOfTable); } } class Item{ String tableType; String colourOfTable; Item(String tableType,String colourOfTable ){ this.tableType=tableType; this.colourOfTable=colourOfTable; } } 

Similar to what you need to do !! Good luck :)

+1
source

Source: https://habr.com/ru/post/949294/


All Articles