You're right, the method doesn't make sens when using a checked type list (generics) and
it's ridiculous trying to add a Float when you know your list expects an int.
When the documentation says "it is possible to defeat this mechanism with unchecked casts.", it doesn't deal with your obvious not permitted cast. It deals with that code :
List list = new ArrayList<>();
Integer i = 3;
Object o = new Float(1.2);
Float f = new Float(2.1);
list.add(i); // warning
list.add(o); // warning
list.add(f); // warning
// list contains [3, 1.2, 2.1]
Then, it says "Usually this is not a problem, as the compiler issues warnings on all such unchecked operations.", that's why your IDE issues warnings. It's legal, it works but has no sens.
Finally, documentation says that "...type checking alone is not sufficient. For example, suppose a collection is passed to a third-party library..." because you can use a type checked collection (to guarantee the type on your side) and pass it to a library that accepts unchecked one. Bad things happens here, the library can do the legal and working bad code we have seen :
public class Library {
public void addNumbers(List list) { // unchecked type
list.add("5");
list.add(Duration.ofMinutes(6));
}
}
public static void main( String[] args ) {
Library library = new Library();
List<Integer> list = new ArrayList<>(); // checked type
Integer i1 = 3;
Integer i2 = 4;
list.add(i1);
list.add(i2);
library.addNumbers(list);
// list contains [3, 4, 5, PT6M]
}
To avoid a third-party adding wrong type values, you must pass it an uncheckedList...
public class Library {
public void addNumbers(List list) {
list.add("5");
list.add(Duration.ofMinutes(6));
}
}
public static void main( String[] args ) {
Library library = new Library();
List<Integer> list = new ArrayList<>();
Integer i1 = 3;
Integer i2 = 4;
list.add(i1);
list.add(i2);
List<Integer> checkedList = Collections.checkedList(list, Integer.class);
library.addNumbers(checkedList); // ClassCastException
}
Notice that if you add value to the checkedList, your initial list will be populated...