2

I already know how to initialize Java HashMap by using one of the following 2 ways

// way 1: apply generic type saftey
HashMap<String, Integer> hashMap1 = new HashMap<String, Integer>();

// way 2: general without apply generic type saftey
HashMap<String, Integer> hashMap2 = new HashMap();

My problem
What is the best practice

According to Eclipse Marker

Type safety: The expression of type HashMap needs unchecked conversion to conform to HashMap

enter image description here So Its recommend to use

new HashMap<String, Integer>(); 

But according to Sonar Linter

Replace the type specification in this constructor call with the diamond operator ("<>").

enter image description here So Its recommend to use

new HashMap();

Which one is the best? Why?

Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88

1 Answers1

5

Use the Java 7 diamond operator:

HashMap<String, Integer> hashMap2 = new HashMap<>();

Diamond <> allows the compiler to infer types implicitly

See: Type Inference for Generic Instance Creation

Anton Hlinisty
  • 1,441
  • 1
  • 20
  • 35