Java-13.13 unbounded wildcards
In this section, we will discuss unbounded wildcards.
1. How to Use unbounded wildcards?
Unbounded wildcards are directly used.
Example:
package com.ray.ch13;import java.util.ArrayList;import java.util.List;public class Test {@SuppressWarnings("unused")private static List list2;public static void test2(List list) {list2 = list;}@SuppressWarnings("rawtypes")public static void main(String[] args) {test2(new ArrayList());// rawtypestest2(new ArrayList
());}}
2. What should I pay attention to when using the unbounded wildcard?
Example:
package com.ray.ch13;import java.util.ArrayList;import java.util.List;public class Test {@SuppressWarnings({ "rawtypes", "unused" })private static List list1;@SuppressWarnings("unused")private static List list2;@SuppressWarnings("unused")private static List list3;@SuppressWarnings({ "unchecked", "rawtypes" })public static void test1(List list) {// rawtypeslist1 = list;list2 = list;list3 = list;// unchecked}public static void test2(List list) {list1 = list;list2 = list;list3 = list;}public static void test3(List list) {list1 = list;list2 = list;list3 = list;}@SuppressWarnings({ "rawtypes", "unchecked" })public static void main(String[] args) {test1(new ArrayList());// rawtypestest2(new ArrayList());// rawtypestest3(new ArrayList());// unchecked/rawtypestest1(new ArrayList
());test2(new ArrayList
());test3(new ArrayList
());// unchecked}}
We carefully observe the above Code and mainly look at the warning to draw the following conclusion:
(1) What is the meaning of using wildcards in List?
It is to tell the compiler that I need to use generics here, but at the moment I have not decided what the type parameter is, it is full configuration for the moment.
(2) Are there any differences between List and List?
Yes.
List, because of the type erasure relationship, List and ListIs equivalent, so List indicates that the type parameter is the List of objects.
List, indicating that the type parameter here is actually specific, but it is not fixed for a moment.
(3) Are there any differences between List and List?
Yes.
List can add any type of objects. List can only add "null" objects.
If you replace List with List, you can add any types of objects.
Summary: This section describes how to use the unbounded wildcard. Of course, due to the limited level of the author, further problems have not yet been found and need to be supplemented later.
This chapter is here. Thank you.