Initialise ArrayList [duplicate] - java

This question already has answers here:
What is the diamond operator in Java?
(2 answers)
Closed 4 years ago.
What's the most right and recommended java expression:
new ArrayList<>();
Or
new ArrayList<String>();
My question goes on any Object that contains any type (like Map).

The first way is valid from Java 7 and you need not to have type init which called as Diamond Operator.
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
The purpose of the diamond operator is to simplify instantiation of generic classes. So just to keep the things simple prefer first way.

Since Java 7, the Diamond operator is used to reduce the verbosity.
If you use version >=7, it is recommended to use the first one.
Go through this.

From Java >= 7 none of them is better than other. The compiler will basically handle them both the same way.
Before Java 7 you had to specificy your Generic Type.
List<String> myStrings = new ArrayList<String>();
But since Java 7, you can do:
List<String> myStrings = new ArrayList<>();
And the compiler is gonna find out the rigth target type for your Collection and inject into your Collection. this is called Type Inference for Generic Instance Creation
Again none is better or recommended above the other, it is just to facilitate your job, so that you write less code. If you are a new java programmer trying to understand the language, you should start with the former. If you are a experienced programmer you do the latter

Related

Java HashMap declaration [duplicate]

This question already has answers here:
What is the point of the diamond operator (<>) in Java?
(7 answers)
Closed 2 years ago.
Hi Guys I have a question about HashMap declaration in Java. I'd like to know what is the difference between:
HashMap<String,Integer> map = new HashMap<>();
and
HashMap<String,Integer> map = new HashMap<String,Integer>();
Most coding websites teach the second one. However, the first one works perfectly fine. Is there a reason we should use second one?
There is technically none, however since Java 1.7 it's a convention to use this <> diamond operator, it reduces the text size.
This is called Type Inference.
Compilers from releases prior to Java SE 7 are able to infer the actual type parameters of generic constructors, similar to generic methods. However, compilers in Java SE 7 and later can infer the actual type parameters of the generic class being instantiated if you use the diamond (<>).
new HashMap<String,Integer>() - The type parameter is mandatory before Java 7
new HashMap<>() - The type parameter is inferred as of Java 7
It's recommended to use the "diamond operator" (<>) due to the brevity. Effectively, there is no difference.
There is no difference between the two of those since form the Java 7. Previously before Java 7 you must mention the Generic type parameters like in your second case in both sides.But to make it easier so that developer can write less code after Java 7 only you need to define it once in the left side.
Before Java Version 7 you need to code like below.
HashMap<String,Integer> map = new HashMap<String,Integer>();//For java versions below 1.7
After Java version 7
HashMap<String,Integer> map = new HashMap<>();//For java versions above 1.7

What is purpose of type on the constructor side of Java collection creation? [duplicate]

This question already has answers here:
Is there a difference between explicitly putting the type into the diamond operator vs letting java figure it out?
(4 answers)
Closed 5 years ago.
What is purpose of re-specifying the type on the right / constructor side of a Java Collection declaration + instantiation?
For example, how is
List<MyClass> a = new ArrayList<MyClass>();
different / better / worse than
List<MyClass> a = new ArrayList<>();
My understanding is the the second form became legal in Java 7, but I still see a lot of examples in Java 7 and 8 where the first form is used.
It is not worse or different. It is the same.
A new and easy way introduced by compiler to reduce human effort of defining of type.

What is the difference between empty generics<> and <E>,<T> notation in java? [duplicate]

The diamond operator in java 7 allows code like the following:
List<String> list = new LinkedList<>();
However in Java 5/6, I can simply write:
List<String> list = new LinkedList();
My understanding of type erasure is that these are exactly the same. (The generic gets removed at runtime anyway).
Why bother with the diamond at all? What new functionality / type safety does it allow? If it doesn't yield any new functionality why do they mention it as a feature? Is my understanding of this concept flawed?
The issue with
List<String> list = new LinkedList();
is that on the left hand side, you are using the generic type List<String> where on the right side you are using the raw type LinkedList. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless
you absolutely have to.
Now, if Java had generics from the beginning and didn't have types, such as LinkedList, that were originally created before it had generics, it probably could have made it so that the constructor for a generic type automatically infers its type parameters from the left-hand side of the assignment if possible. But it didn't, and it must treat raw types and generic types differently for backwards compatibility. That leaves them needing to make a slightly different, but equally convenient, way of declaring a new instance of a generic object without having to repeat its type parameters... the diamond operator.
As far as your original example of List<String> list = new LinkedList(), the compiler generates a warning for that assignment because it must. Consider this:
List<String> strings = ... // some list that contains some strings
// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);
Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.
// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);
The diamond operator, however, allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left side... without having to type those parameters again. It allows you to keep the safety of generics with almost the same effort as using the raw type.
I think the key thing to understand is that raw types (with no <>) cannot be treated the same as generic types. When you declare a raw type, you get none of the benefits and type checking of generics. You also have to keep in mind that generics are a general purpose part of the Java language... they don't just apply to the no-arg constructors of Collections!
Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.
Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.
Using List<String> list = new LinkedList() will get you rawtype warnings.
This line causes the [unchecked] warning:
List<String> list = new LinkedList();
So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?
I think, it would be much more difficult task then adding <> feature.
UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.
In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?
No sane programmer uses raw types in new code. So the compiler could simply assume that by writing no type arguments you want it to infer them.
The diamond operator provides no type information, it just says the compiler, "it'll be fine". So by omitting it you can do no harm. At any place where the diamond operator is legal it could be "inferred" by the compiler.
IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.
Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as
package 7 com.example;
could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.
When you write List<String> list = new LinkedList();, compiler produces an "unchecked" warning. You may ignore it, but if you used to ignore these warnings you may also miss a warning that notifies you about a real type safety problem.
So, it's better to write a code that doesn't generate extra warnings, and diamond operator allows you to do it in convenient way without unnecessary repetition.
All said in the other responses are valid but the use cases are not completely valid IMHO. If one checks out Guava and especially the collections related stuff, the same has been done with static methods. E.g. Lists.newArrayList() which allows you to write
List<String> names = Lists.newArrayList();
or with static import
import static com.google.common.collect.Lists.*;
...
List<String> names = newArrayList();
List<String> names = newArrayList("one", "two", "three");
Guava has other very powerful features like this and I actually can't think of much uses for the <>.
It would have been more useful if they went for making the diamond operator behavior the default, that is, the type is inferenced from the left side of the expression or if the type of the left side was inferenced from the right side. The latter is what happens in Scala.
The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.
The only difference if you specify in Java 5 and 6,
List<String> list = new ArrayList();
is that you have to specify #SuppressWarnings("unchecked") to the list (otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.

What is the difference between "ArrayList<String> = new ArrayList<>()" and "ArrayList<String> = new ArrayList<String>()"? [duplicate]

This question already has answers here:
What is the diamond operator in Java?
(2 answers)
Closed 7 years ago.
just like the title said, in Java, is there any difference between the two statements?
Usually I can see the two statements both. So I suppose there may be no difference. But could you help to confirm and explain why they are identical?
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al = new ArrayList<>();
Thanks!
They are identical. new ArrayList<String>(); was required prior to JDK 7. In JDK 7 they introduced the 'diamond operator', where the type is inferred.
So, if you are using JDK 7+ you can simply use new Arraylist<>()
You can see this in the Java Language Specification under Class Instance Creation Expressions, or search for 'Diamond Operator'
This is a Diamond Operator.
The Diamond Operator reduces some of Java's verbosity surrounding generics by having the compiler infer parameter types for constructors of generic classes.
http://www.javaworld.com/article/2074080/core-java/jdk-7--the-diamond-operator.html
In java 7 and later there is no difference. The latter is considered more concise.
The so called diamond operator <> is helping here for the type to be inferred.

Explicit specification of Arraylists

Is the explicit specification of array lists considered as a bad practice since Java7? Why is it unneccessary from this version?
List<String> foo = new Arraylist<String>(); // before
List<String> bar = new Arraylist<>(); // from Java7
Is it just because it's defined in the List?
Thanks!
Is the explicit specification of array lists considered as a bad practice since Java7?
It's not "bad practice" - it's just a little more longwinded than it might be. The two statements have exactly the same effect, so there's no downside to the longer version in that sense. You definitely don't need to go around "fixing" all your old code - but you may choose to use the shorter form when you're editing existing code anyway, or writing new code.
Why is it unneccessary from this version?
Because Java 7 introduced the "diamond operator" (not actually an operator at all) precisely to avoid having to specify type arguments redundantly. From the Oracle documentation on "Type Inference for Generic Instance Creation":
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
This isn't the only new feature in Java 7 from a language perspective - again, see the documentation for details.
I dont think its a bad practice, its just a way of giving ease to the programmer.. Consider this
Map<List<String>,Map<String,Integer>> superMap = new HashMap<>();
the same should have been written as
Map<List<String>,Map<String,Integer>> superMap = new HashMap<List<String>,Map<String,Integer>>();
in Java 6, where the later generic substitution is redundant
The new format just helps you to save some keystrokes. So in Java 7 when you write
List<String> bar = new Arraylist<>();
which is considered equal to
List<String> foo = new Arraylist<String>();
Compiler will automatically infer the types from the left hand side when diamond operator is used.

Categories