50,528
社区成员
发帖
与我相关
我的任务
分享
List<Integer> listI = new ArrayList<>();
第一句能这样写吗?很明显的错误。你运行一下,看能不能取出Test。
一个类实现了Camparable接口则表明这个类的对象之间是可以相互比较的,这个类对象组成的集合就可以直接使用sort方法排序。
Comparator可以看成一种算法的实现,将算法和数据分离,Comparator也可以在下面两种环境下使用:
1、类的设计师没有考虑到比较问题而没有实现Comparable,可以通过Comparator来实现排序而不必改变对象本身
2、可以使用多种排序标准,比如升序、降序等
具体应用实例可以参考:http://blog.csdn.net/h70614959/article/details/17115355
如何把非 Comparable 的对象作为 TreeMap 的 Key:
这句是JDK对TreeMap的解释.
java.util
Class TreeMap<K,V>
java.lang.Object
extended by java.util.AbstractMap<K,V>
extended by java.util.TreeMap<K,V>
Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values
All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
再看一下TreeMap的构造函数,相信大家已经明白了。
TreeMap(Comparator<? super K> comparator)
Constructs a new, empty tree map, ordered according to the given comparator.
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
((List) list).add(8);//泛型擦除放入
System.out.println(((List) list).get(0));//泛型擦除取出
}
List<String> list = new ArrayList<>();
((List)list).add(new Integer(100));
第四题,好吧,我记错了,两个都是接口,Comparator 多个equals()方法。
但是TreeMap构造器可以指定Comparator。
public TreeMap(Comparator<? super K> comparator)
[/quote]
new List<Integer>()
和new List()
的概念能一样么?List原生类型加上自动装箱放什么不行?List<Integer>是Integer的列表的意思,不是你new List().add(new Integer())[/code]它就叫List<Integer>,放个String叫它List<String>也行啊。