Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
null
и Exception
( habrahabr.ru/post/146042/ и habrahabr.ru/post/155477/ см. про класс Either<Resut, Error>
и Option<Resut>
).null
самое плохое — на концептуальном уровне: возвращать null
или кидать NPE — непонятно.This is way too risky to fix in a jdk6 update release.
Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.
тут корректнее говорить не про Map/Set, а про конкретные реализации.
Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException.
Ответ №2: В пустой TreeMap можно положить единственный ключ-null, все остальные операции (кроме size() и clear(), кстати) после этого не работают. В непустой TreeMap положить null-ключ нельзя из-за обязательного вызова compareTo().Я с таким ответом не согласен. Правильный ответ будет следующим:
К примеру, в WinAPI есть функции, где в ранних версиях в документации какой-то параметр был описан как «reserved, must be 0».
Очевидно, такое поведение недокументировано, а значит, может измениться.Как-то раз я чуть не начал проходить собеседование в Oracle, в подразделение, занимающееся тестированием их родной Java-машины. Спасибо, вы меня натолкнули на понимание фразы интервьюера о «тестах, которые должны падать». Это как раз про такое поведение. Если его исправить, то с большой вероятностью у кучи народа всё повалится в production-е. Поэтому лучше отложить до следующей версии. А тесты на него уже есть.
Map map = new TreeMap();
map.put(null, "null"); // ошибки нет!
Java собеседование. Коллекции vs null