-
List class methods
Object
equals()
hashCode()
toString()
getClass()
notify()
notifyAll()
wait()
wait(long timeOut)
wait(long timeOut, int nanos)
-
equals
Why are & methods neededhashCode
?Used to compare objects.
The purpose of the method
equals
is to determine whether objects are internally identical by comparing the internal contents of the objects. Thisequals
works slowly, first the hash codes of the objects are compared, and if the hash codes are equal, a check is made againstequals
-
What happens if you override equals but not override
hashCode
?Initially
hashCode
, a random number.equals
Collections in Java always look for/compare them using the method before comparing objects usinghashCode()
. And if identical objects have differenthashCode
, then the objects will be considered different - it simply won’t be possible to compare using themequals
. -
Why are the methods
wait
,notify
,notifyAll
?Sometimes a program may have a situation where a thread has entered a block of code
synchronized
, blocked the monitor, and cannot work further, because some data is still missing: for example, the file that it should process has not yet been loaded or something like that. A method was invented to solve this problemwait()
. Calling this method causes the thread to release the monitor and "pause".To unpause, methods are used
notify
.notifyAll
The methodnotify
“unfreezes” one random thread, the methodnotifyAll
– all “frozen” threads of a given monitor. -
How to clone an object correctly?
Two types of cloning.
To clone a default object:
- Add an interface
Cloneable
to your class - Override the method
clone
and call the base implementation in it:
class Point implements Cloneable { int x; int y; public Object clone() { return super.clone(); } }
Or you can write the implementation of the method
clone
yourself:class Point { int x; int y; public Object clone() { Point point = new Point(); point.x = this.x; point.y = this.y; return point; } }
- Add an interface
-
Why is the method needed
finalize()
and how does it work?If you remember, this
finalize()
is a special method that is called on an object before the garbage collector destroys it.The main purpose of this method is to release used external non-Java resources: close files, I/O streams, etc.
finalize()
works unstable.This method does not live up to the expectations placed on it. The Java machine can delay the destruction of an object, as well as the call of a method,
finalize
for as long as it likes. Moreover, it does not guarantee that this method will be called at all. In a lot of situations, for the sake of “optimization” it is not called. -
What is the difference
final
,finally
,finalize
?final
- modifier- Fields cannot be changed, methods are overridden
- Classes cannot be inherited
- This modifier only applies to classes, methods and variables (also local variables)
- Method arguments marked as are
final
read-only; attempting to change them will result in a compilation error. - Переменные
final
не инициализируются по умолчанию, им необходимо явно присвоить meaning при объявлении or в конструкторе, иначе – ошибка компиляции - Если final переменная содержит ссылку на an object, an object может быть изменен, но переменная всегда будет ссылаться на тот же самый an object
- Также это справедливо и для массивов, потому что массивы являются an objectми, – массив может быть изменен, а переменная всегда будет ссылаться на тот же самый массив
- Если класс объявлен
final
иabstract
(взаимоисключающие понятия), произойдет ошибка компиляции - Так How
final
класс не может наследоваться, его методы никогда не могут быть переопределены
finally
— блок в связкеtry-catch-finally
, code в котором выполнится независимо от того вылетело ли исключение в блокеtry
or нет. Используется для освобождения ресурсов.finalize
— метод в классеObject
см 6. -
What такое
try-with-resources
?Это специальная конструкция
try
, называемаяtry-with-resources
, в которой Обрати внимание – послеtry
следуют круглые скобки, где объявляются переменные и создаются an objectы. Эти an objectы можно использовать внутри блокаtry
, обозначенного скобками{}
. Когда выполнение команд блокаtry
закончится, независимо от того – нормально оно закончилось or было исключение, для an object, созданного внутри круглых скобок()
, будет вызван методclose()
; -
Чем отличаются методы
wait(1000)
иsleep(1000)
?sleep()
приостанавливает поток на указанное. состояние меняется на TIMED_WAITING, по истечению — RUNNABLEwait()
меняет состояние потока на WAITINGможет быть вызвано только у an object владеющего блокировкой, в противном случае выкинется исключение IllegalMonitorStateException. при срабатывании метода блокировка отпускается, что позволяет продолжить работу другим потокам ожидающим захватить ту же самую блокировку . в случае
wait(int)
с аргументом состояние будет TIMED_WAITING -
В чем отличие
i++
и++i
?++i
,i
сначала увеличивается на 1, затем участвует в выражении.i++
,i
сначала участвует в выражении, затем увеличивается на 1.
GO TO FULL VERSION