Collections.singleton()在进行remove操作时抛出UnsupportedOperationException异常原因
- 这个方法主要用于只有一个元素的优化,减少内存分配,无需分配额外的内存。返回一个只读的Set集合,这个集合是Collections的内部类,继承了AbstractSet,AbstractSet中有removeAll方法,但是singleSet的迭代器实现的时候对remove方法抛了异常。
- 该类没有提供add方法
- 类似的还有Collections的一系列sinletonList、SingletonMap等方法。
-
- AbstractSet只有equals、hashCode和removeAll方法
- AbstractSet只有equals、hashCode和removeAll方法
- Arrays.asList方法返回的集合,继承了AbstractList,但是没有重写add和remove方法,父类中的该方法,均抛出异常
-