Problems with strong conversion of Collections
See the followingCode:
Private list <jobinfo> mjoblist;
Mjoblist = collections. synchronizedlist (New arraylist <jobinfo> ());
This method is correct, because the returned value of the synchronizedlist method is the list set.
Private arraylist <jobinfo> mjoblist;
Mjoblist = (arraylist <jobinfo>) collections. synchronizedlist (New arraylist <jobinfo> ());
This statement looks correct and will actually report an exception"Caused by: Java. Lang. classcastexception: Java. util. Collections $ synchronizedrandomaccesslist"
Analysis:
1. What does the <t> List <t> of a function mean?
What I know is that a collection of the list type is returned, and the type of the object stored in it is t, but what does the previous <t> mean?
In this generic method, the type parameter is T, which is located after all the modifiers of the function and before the return value is placed in angle brackets. This T is the type parameter of the function, t in list <t> is the type parameter of this set.
List <t>: Return Value of parameterized type.
Next let's take a look at the source code of the synchronizedlist method:
Public static <t> List <t> synchronizedlist (list <t> List ){
If (list = NULL ){
Throw new nullpointerexception ();
}
If (list instanceof randomaccess ){
Return new synchronizedrandomaccesslist <t> (list );
}
Return new synchronizedlist <t> (list );
}
Mjoblist = (arraylist <jobinfo>) collections. synchronizedlist (New arraylist <jobinfo> (); in this line of code, a parameter of the arraylist type is passed to the synchronizedlist method. arraylist implements the randomaccess interface, so
Will Execute return New synchronizedrandomaccesslist <t> (list); this line of code, let's look at the UML class diagram, where synchronizedrandomaccesslist, synchronizedlist, synchronizedcollection is a static internal class of the collections tool class.
From this figure, we can see that synchronizedrandomaccesslist is a sub-class of list, which is not of the arraylist type. Therefore, the strong conversion of the above Code is incorrect. In addition, we can see that this is a packaging mode, write the package mode later.