I have a task, which I was able to do with the use of simplest methods – arrays. Now I’d like to go further and redo it using some more complicated java features like collections, but I’ve never used anything more complicated than 2d matrix. What should I look at and how to start with it. Should Tower become a Collection ? And here’s the task :
We have two classes – Tower and Block. Towers are built from Blocks.
Ande here’s sample code for testing:
Block k1=new Block("yellow",1,5,4);
Block k2=new Block("blue",2,2,6);
Block k3=new Block("green",3,4,2);
Block k4=new Block("yellow",1,5,4);
Tower tower=new Tower();
tower.add(k1,k2,k3);
"Added 3 blocks."
System.out.println(tower);
"block: green, base: 4cm x 3cm, thicknes: 2 cm
block: blue, base: 6cm x 2cm, thicknes: 2 cm
block: yellow, base: 5cm x 4cm, thicknes: 1 cm"
tower.add(k2);
"Tower already contains this block."
tower.add(k4);
"Added 1 block."
System.out.println(tower);
"block: green, base: 4cm x 3cm, thicknes: 2 cm
block: blue, base: 6cm x 2cm, thicknes: 2 cm
block: yellow, base: 5cm x 4cm, thicknes: 1 cm
block: yellow, base: 5cm x 4cm, thicknes: 1 cm"
tower.delete(k1);
"Deleted 1 block"
tower.delete(k1);
"Block not in tower"
System.out.println(tower);
"block: blue, base: 6cm x 2cm, thicknes: 2 cm
block: yellow, base: 5cm x 4cm, thicknes: 1 cm
block: yellow, base: 5cm x 4cm, thicknes: 1 cm"
Let’s say I will treat Tower as a collection of blocks. How to perform search for specific block among whole collection ? Or should I use other interface ?
You can use as collection a Set which prevents duplicate elements.
It will return
falseif you try to add an element which is already present.To know if the set already contains an element the class should implement correctly the equals() method.
To provide the description messages you may override the toString() method and iterate the set: