JavaRush /Java Blog /Random EN /Level 35. Answers to interview questions on the level top...
Afli
Level 41
Санкт-Петербург

Level 35. Answers to interview questions on the level topic

Published in the Random EN group
Questions/additions/criticism are welcome. Level 35. Answers to interview questions on the topic of level - 1
  1. What version control systems do you know?

    Git, SVN, Bazaar, Mercurial

  2. How are SVN and Git different?

    1. GIT is a distributed VCS, but SVN is not. In other words, if there are several developers working with a repository, each will have a FULL copy of this repository on their local machine. Of course, there is also a central machine from which you can clone the repository. This is reminiscent of SVN. The main advantage of Git is that if suddenly you do not have access to the Internet, you can still work with the repository. Then just do the synchronization once and all other developers will receive the full history.

    2. GIT stores change metadata, while SVN stores entire files. This saves space and time.

  3. What is GitHub? Do you have projects on GitHub?

    GitHub is a web-based project hosting service using the git version control system, as well as a social network for developers. Users can create an unlimited number of repositories, for each of which a wiki is provided, an issue tracking system is provided, it is possible to conduct code reviews, etc. In addition to Git, the service supports receiving and editing code via SVN and Mercurial.

  4. Why do we need version control systems?

    VCS makes it possible to return individual files to their previous form, return the entire project to its previous state, view changes occurring over time, determine who was the last to make changes to a module that suddenly stopped working, who and when introduced some kind of error into the code, etc. .. In general, if, using VCS, you ruin everything or lose files, everything can be easily restored.

  5. What is generic? How are they implemented in Java?

    Generics are parameterized types. With their help, you can declare classes, interfaces and methods, where the data type is specified as a parameter. Generics added type safety to the language.

    Example implementation:

    class MyClass<T>{
      T obj;
      public MyClass(T obj){
        this.obj = obj;
      }
    }
    class MyClass<T>

    The angle brackets use T , the name of the type parameter. This name is used as a placeholder for the name of the real type passed to the class MyClasswhen creating real types. That is, the type parameter Tis used in the class whenever a type parameter is required. Angle brackets indicate that the parameter can be generalized. The class itself is called a generic class or parameterized type.

    Next, the type Tis used to declare an object by name obj:

    T obj;

    Instead, Tthe real type will be substituted, which will be specified when creating an object of the class MyClass. The object objwill be an object of the type passed in the type parameter T. If Tyou pass the type as a parameter String, the instance objwill have the type String.

    Consider the constructor MyClass():

    public MyClass(T obj){
      this.obj = obj;
    }

    Параметр obj имеет тип T. Это значит, что реальный тип параметра obj определяется типом, переданным параметром типа T при создании an object класса MyClass.

    Параметр типа T также может быть использован для указания типа возвращаемого значения метода.

    В именах переменных типа принято использовать заглавные буквы. Обычно для коллекций используется буква E, буквами K и V — типы ключей и meaning (Key/Value), а буквой T (и при необходимости буквы S и U) — любой тип.

    Обобщения работают только с an objectми. Поэтому нельзя использовать в качестве параметра elementрные типы вроде int or char.

    *Так же считаю нужным упомянуть generic методы. Это методы вида:

    модификаторы <T, ...> возвращаемыйТип method name(T t, ...)

    Как я понял, если в качестве типа в сигнатуре метода используются параметры, необходимо перед типом возвращаемого значения их перечислить. Верно ли это?

    Более подробную информацию можно посмотреть по следующим linkм:

  6. What такое стирание типов?

    Внутри класса-дженерика не хранится информация о его типе параметре. Это и называется стиранием типов. На стадии компиляции происходит приведение an object класса к типу, который был указан при объявлении.

    Пример:

    Level 35. Answers to interview questions on the topic of level - 2
  7. What такое wildcard?

    Wildcard — это дженерик вида <?>, что означает, что тип может быть чем угодно. Используется, например, в коллекциях, где для всех коллекций базовым типом является Сollection<?>.

    Полезная link: Теория и практика Java. Эксперименты с generic-методами

  8. Расскажите про extends и super в Generic'ах?

    Whatбы наложить ограничение на wildcard необходимо использовать конструкции типа:

    • ? extends SomeClass — означает, что может быть использован любой класс-наследник SomeClass
    • ? super SomeClass — означает, что может быть использован класс SomeClass, либо класс-родитель (or интерфейс) SomeClass

    Это называется bounded wildcard.

    Для того, чтобы определиться с выбором между extends и super был придуман метод PECS.

    Подробно про это можно прочитать по ссылке ниже: Использование generic wildcards для повышения удобства Java API

  9. Как использовать wildcard?

    Пример использования wildcard:

    List<?> numList = new ArrayList<Integer>();

    Вопрос я не понял, но в принципе использование wildcard’ов рассматривается в материалах по linkм выше.

  10. В чем отличие ArrayList и ArrayList<?>

    Запись вида ArrayList называется raw type (обычный тип). Она эквивалентна записи вида ArrayList<T> и используется для обратной совместимости, т.к. до Java 1.5 не было дженерик коллекций. По возможности такой формы записи следует избегать.

    ArrayList<?> является супертипом для ArrayList.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION