Store interface in java array list

I am learning java. I am trying to use a composite design pattern. I am trying to use the following logic. (Do not laugh, I know that it is very simple :))

Item -> interface Folder -> class File -> class 

In a folder class, can I create an arraylist element to store file information?

 ArrayList<Item> info = ArrayList<Item>(); 

Or do I need to use a Folder Arraylist?

 ArrayList<Folder> info = ArrayList<Folder>(); 

I do not know if the interface can store real data, since there is no function definition variable.

Thanks for the help to the beginner :)

+4
source share
4 answers

You can do both (with some syntax correction)

 List<Item> info = new ArrayList<Item>(); 

Regarding this comment:

I do not know if the interface can store real data, since there are no definitions just for defining variables.

Interfaces are more than function definitions provide. Most importantly, they determine the type. info declared above is a list of objects of type Item . These objects can certainly store data.

As an example, consider the following:

 interface Item { ... } class Folder implements Item { ... } Item it = new Folder(); 

Now it refers to the instance of the Folder , which is Item .

+4
source

While Folder and File implement Item , this will work fine. However, keep in mind that you will have access to the properties that are defined in the Item interface: not those related to Folder or related to File .

From what you described, this sounds like a reasonable way to approach the problem, although it's hard to say for sure without knowing more about using this data structure.

+1
source

You can certainly create an ArrayList of elements. It is not a problem that Item, as an interface, does not have instance variables. However, the only elements that can be created are not "just" elements - they will be instances of some class that implements interface of the element. So, for example, if Folder and File implement the Item interface, you can put both folders and files in this ArrayList. But an ArrayList will be declared simply for storing items - and since they implement this interface, both Folders and Files Qualify are Items.

+1
source

The interface cannot store data. An interface is a type that you can use as a contract that your file and folder classes will implement. Since the Item interface is implemented in your files and folders, you can add files and folder objects to the list that accepts the item type.

 List<Item> info = new ArrayList<Item>() 
+1
source

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


All Articles