Menu

You Called remove(4) and Java Took Out the Fifth Item
📰

You Called remove(4) and Java Took Out the Fifth Item

DEV Community: java·Serguey Asael Shinder·12 days ago
#NsjhHcWl
#devtojava#devto#dev#remove#table
Reading 0:00
15s threshold

The booking code was small.

A list of open tables.

When a table is booked,

take its number out of the list.

openTables.remove(tableNumber).

It read like English.

It passed the tests,

because the test booked table one

in a list that started with table one.

Then Friday night.

Table four was booked twice.

Table five

was marked as taken

with nobody sitting at it.

And once in a while,

booking table eighteen

threw an IndexOutOfBoundsException

and the waiter tried again.

Here is the mechanism.

A Java List has two methods

called remove.

remove(int index)

takes out whatever is at that position.

remove(Object o)

looks for that value

and takes it out.

Your list held Integers.

Your table number was an int,

straight from getTable().

When the compiler picks an overload,

it first looks for a method

that fits without boxing.

remove(int) fits exactly.

So it wins,

every time,

and nothing warns you.

remove(4)

did not remove the table numbered four.

It removed the fifth element,

which,…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.