Java Collections checkedCollection() MethodThe checkedCollection() is a method of Java Collections class which returns a dynamically typesafe view of the specified collection. If an element inserted of the wrong type, it will result in an immediate ClassCastException. SyntaxFollowing is the declaration of checkedCollection() method: Parameter
ReturnsThe checkedCollection() method returns a dynamically typesafe view of the specified collection. ExceptionsClassCastException Compatibility VersionJava 1.5 and above Example 1Test it NowOutput: Type safe view is: [A, B, C, D] Example 2Test it NowOutput: Type safe view is: [10, 20, 30, 40] Example 3Test it NowOutput: [apple, banana] Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String at java.base/java.util.Collections$CheckedCollection.typeCheck(Collections.java:3038) at java.base/java.util.Collections$CheckedCollection.add(Collections.java:3081) at myPackage.CollectionCheckedCollectionExample3.main(CollectionCheckedCollectionExample3.java:12) Next TopicJava Collections Class |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India