@Test public void TypeInferenceTest() { inference(); uncheckedAssignment(); explicit(); } private void inference() { ArrayList<String> strings = new ArrayList<>(); strings.add("abc"); String s = strings.get(0); assertThat(s, is("abc")); } private void uncheckedAssignment() { ArrayList<String> strings = new ArrayList(); strings.add("abc"); String s = strings.get(0); assertThat(s, is("abc")); } private void explicit() { ArrayList<String> strings = new ArrayList<String>(); strings.add("abc"); String s = strings.get(0); assertThat(s, is("abc")); } The code above used three ways to instantiate a list: type inference, open generic type and closed generic type.
But if I decompile the generated bytecode using JD-GUI, this is the result:
@Test public void TypeInferenceTest() { inference(); uncheckedAssignment(); explicit(); } private void inference() { ArrayList strings = new ArrayList(); strings.add("abc"); String s = (String)strings.get(0); Assert.assertThat(s, Matchers.is("abc")); } private void uncheckedAssignment() { ArrayList strings = new ArrayList(); strings.add("abc"); String s = (String)strings.get(0); Assert.assertThat(s, Matchers.is("abc")); } private void explicit() { ArrayList strings = new ArrayList(); strings.add("abc"); String s = (String)strings.get(0); Assert.assertThat(s, Matchers.is("abc")); } Looks like they generated the same bytebote.
So when and why should we use type inference instead of the other two?