变量宣言、函数返回一般用通用型
例如:
SetString list=new HashSet (; ListString list=new ArrayList (; ArrayList的本质是通过数组实现的,检查某个元素是否包含用于遍历的元素。 时间复杂度为o(n ),而HashSetHashSet的搜索由HashMap的KeySet实现,判断是否含有某个要素。 时间复杂度为o )1)
ArrayList确定是否包含元素的源代码实现:
公共布尔索引(对象)返回索引of )=0; }公共int index of (objecto ) if ) o==null ) for ) intI=0; i size; I ) if (元素数据[ I ]==null )返回I; (else ) for ) intI=0; i size; I )//if(o.equals ) elementdata[I] )返回I; }返回- 1; } HashSet确定是否包含元素的源代码实现。
publicbooleancontains(objecto ) returnmap.containskey ) o; }公共布尔连续密钥(对象密钥)返回节点(hash(key ),key )!=null; ) } final NodeK,vgetnode(inthash,Object key ) { NodeK,V[] tab; 节点,V first,e; int n; k; if ()选项卡=选项卡)!=null(n=tab.Length )0) first=tab((n-1 ) hash] )!=null () /直接用hash确定元素位置,从头开始if(first.hash )==hash//alwayscheckfirstnode ) (k=first.key )|) key!=空密钥. equals (k ) ) (return first; if () e=first.next )!=null () if(firstinstanceoftreenode ) return () treenodek,first ).gettreenode ) hash,key ); do{if(e.hash==hash () k=e.key )==key||(key!=nullkey.equals(k ) ) ) ) ) /在某些情况下,您可能会继续遍历链表以搜索返回e。 }while((e=e.next )!=null; } }返回空值; }