Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
wildcard. The collection removeAll() method is such an example. In most cases, this
usage is self-explanatory. You probably won’t be (probably shouldn’t be) defining your own parameterized types using an unbounded wildcard. If you try to do this, you soon learn there isn’t much you can do with it. If you understand concrete parameterized types, wildcard parameterized types, and the concept of bounded and unbounded types, as described in this recipe, you have most of what you need to work with the generic collection types and create your own generic types if you so choose. Now that we’ve talked a lot about parameterizing types, we’re going to tell you to forget about some of them. When Java 7 was released, a new feature called the diamond (sometimes referred to as the diamond operator, although it is not considered an operator in Java) was introduced. The diamond allows the compiler to infer the type argument(s) from the context of the parameterized type usage. A simple example of diamond usage follows. List Notice there is no type argument specified between the angle brackets when instantiating the ArrayList. The compiler can easily infer the type to be an integer based on the context of the assignment or initializer. Integer is the only type that would work in this context. In fact, the Java compiler (and most compliant IDEs) warn you if you do not use a diamond where it is possible to use it. Another more complex example shows the benefit even better. Map The diamond can similarly be used in return statements, as well as in method arguments. // diamond in method return public static List return new ArrayList<>(); } // diamond in method argument List
gList.set(0, new ArrayList<>(Arrays.asList("a", "b"))); Chapter 7 Data SourCeS anD ColleCtionS 268 Note that using the diamond as shown here is different from using a raw type. The following is not equivalent to the declaration of aMap that uses the diamond; it result in an “unchecked conversion” warning, and possibly a raw type warning, from the compiler. Map avoid raw types The discussion around why this is different from the diamond example is beyond the scope of this recipe. If you remember to avoid the use of raw types, you shouldn’t need to worry about this. Use the diamond whenever possible to save yourself some typing and make your code more robust, readable, and concise. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling