JavaRush /Java Blog /Random EN /Level 36. Answers to interview questions on a level topic...
Level 40

Level 36. Answers to interview questions on a level topic

Published in the Random EN group
Again, I searched everything and couldn’t find any answers. Well. I’ll post mine, although I wrote them purely for myself, and if possible, briefly. But anything is better than nothing. So, there were the following questions: Level 36.  Answers to questions for an interview on a level - 1 topicQuestions for the interview:
  1. What is MVC ?
  2. What are DAO and DTO ?
  3. What is POJO ?
  4. What is Entity ?
  5. What list collections do you know?
  6. What collections-sets do you know?
  7. What is a map , how does it differ from a “ dictionary ”?
  8. What are Queue and Dequeue ?
  9. What classes that implement the Queeue interface do you know?
  10. What is a tree ?
And now my answers:
  1. MVC is an application design pattern in which the application is divided into three separate parts: model, view, and controller. The model provides data and responds to controller commands by changing its state. The view is responsible for displaying model data to the user, responding to changes in the model. And the controller interprets the user’s actions, notifying the model about the need for changes. Thus, each of the components of this circuit is loosely coupled with other components, thereby achieving program flexibility. Most often, all business logic is contained in the model, although sometimes it is also contained in the controller. In the first case, the model is called thin, in the latter - thick.

  2. DAO (Data Access Object) is an object whose main task is to save data into a database, as well as retrieve it from it. DTO (Data Transfer Object) is an object designed to transport data. Therefore, its main task is to store this data. It doesn't contain any logic. In addition, it must be serializable, since transporting objects usually occurs through serialization-deserialization.

  3. POJO stands for "Old Style Java Object". They are contrasted with EJB objects. The latter follow a special convention and are usually strictly tied to a specific enterprise framework (for example, they must have a public constructor without parameters, they must have getters and setters for fields, they must be serializable, etc.). POJO is, accordingly, a regular class that does not inherit from any special classes and does not implement any special libraries. Typically a POJO doesn't do anything special and only contains state.

  4. An Entity Bean is a bean whose purpose is to store some data. The logic of such a bean has a built-in mechanism for saving itself and its fields to the database. Such an object can be destroyed and then recreated from the database again. But other than storing data, it has no logic. A bean, in turn, is a special class that must comply with the following rules:

    • The class must have a parameterless constructor with the public access modifier. This constructor allows tools to create an object without the added complexity of parameters.
    • Properties of a class must be accessible through get, set, and other methods (called accessors), which must follow a standard naming convention. This easily allows tools to automatically detect and update the content of beans. Many tools even have specialized editors for different types of properties.
    • The class must be serializable. This makes it possible to reliably save, store, and restore bean state in a platform- and virtual-machine-independent manner.
    • The class must have equals(), hashCode() and toString() methods overridden.
  5. All list collections implement the List<E> interface and inherit from the abstract class AbstractList<E>. Among them are ArrayList<E> and LinkedList<E7gt;. ArrayList7lt;E> is an array-based list, while LinkedList<E> is a classic doubly linked list.

  6. Коллекции-множества в Java реализуют интерфейс Set<E> и наследуются от AbstractSet<E>. Множества — это такие наборы данных, в которых все элементы уникальны. Среди них в Java есть HashSet, LinkedHashSet и TreeSet. Первая коллекция хранит свои an objectы на основе хеш-codeов. Вторая — это модифицированная первая, в ней элементы ещё к тому же располагаются в связном списке, поэтому они все расположены в порядке добавления. Третья коллекция обеспечивает сортировку своих элементов.

  7. Map — это вид коллекций, хранящих свои элементы в виде пар "ключ-значения". Причём все ключи должны быть уникальными. Среди реализаций есть HashMap и TreeMap. Первая реализация хранит элементы с использованием хэш-codeов. Вторая - хранит элементы в отсортированном по ключу порядке.

  8. Очередь (Queue) — это структура данных, работающая по принципу "Первый вошёл — первый вышел". То есть элементы в очередь добавляются с одного конца, а извлекаются — с другого. Deque — это двусторонняя очередь. В этой очереди элементы можно добавлять How в начало, так и в конец, а также брать элементы тоже можно и из начала, и из конца очереди. Соответственно есть методы, которые позволяю положить элемент (это методы add(e) и offer(e)), и есть методы, позволяющие извлечь элемент из очереди (это такие методы, How remove() и poll()). Кроме того, есть методы, которые позволяют просто получить элемент из очереди без его удаления оттуда (это методы element() и peek()). В интерфейсе Deque дополнительно есть методы для добавления элементов в начало и конец очереди, извлечения элементов из начала or конца, а также получения элементов из начала or конца очереди (без их удаления из очереди).

  9. Среди простых реализаций можно отметить ArrayDeque, LinkedList и PriorityQueue. Также существуют много классов в Concurrent Collections, которые реализуют эти два интерфейса (оба сразу or только один из них).

  10. A tree is a connected graph without loops or multiple edges. Typically, if there are N vertices in a tree, then the number of edges is at least N-1. Also, one vertex in the tree is chosen as the root. The remaining vertices are declared branches. Branches that do not have branches of their own are called leaves of a tree.
    Trees are used quite widely in programming, and many types of this tree have already been invented. One of the most widely used trees is the binary tree. In this tree, each element has at most two children (that is, there can be from 0 to 2). One type of binary tree is BST - binary search tree. In this tree, a rule is imposed on the elements: the left child of the element must be less than it in value, and the right child must be greater than or equal to it in value.
    There are also red-black trees. This is a type of binary search tree. In red-black trees, another property of the element is introduced - color. The color can be black or red. Also, each red-black tree must satisfy the following requirements:

    1. the root of the tree is black;
    2. the node is either red or black;
    3. all the leaves of the tree are black;
    4. both descendants of the red node are black;
    5. Every path from a given node to any leaf node that is its descendant contains the same number of black nodes.
These rules allow you to achieve a balanced tree. A tree is balanced when the length of the path from the root to any leaf node differs by no more than 1. (That is, in simple terms, there are no distortions or long branches in the tree.)