Java HashMap isEmpty() Method
The isEmpty() method is used to check whether the HashMap is empty.
The syntax of the isEmpty() method is:
hashmap.isEmpty()
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- None
Return Value
Returns true if the HashMap contains no key/value pair mappings, otherwise returns false.
Example
The following example demonstrates the use of the isEmpty() method:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
HashMap
<
Integer
, String
sites
=
new
HashMap
<>
(
)
;
// Check whether the HashMap contains elements
boolean
result
=
sites.
isEmpty
(
)
;
// true
System
.
out
.
println
(
"Is empty? "
result
)
;
// Add some elements to the HashMap
sites.
put
(
1
,
"Google"
)
;
sites.
put
(
2
,
"Runoob"
)
;
sites.
put
(
3
,
"Taobao"
)
;
System
.
out
.
println
(
"HashMap: "
sites
)
;
result
=
sites.
isEmpty
(
)
;
// false
System
.
out
.
println
(
"Is empty? "
result
)
;
}
}
The output of the above program is:
是否为空? true
HashMap: {1=Google, 2=Runoob, 3=Taobao}
是否为空? false
In the above example, we created a HashMap named sites, and then used the isEmpty() method to check whether it is empty.
Java HashMap