7 8 9 collections - york university...add(e e) on a set returns false if e is already in it (for a...
TRANSCRIPT
Collec&ons
EECS1022/Lespérance 1
EECS1012MOBILECOMPUTING
PROF.Y.LESPÉRANCEDept.ofElectricalEngineering&ComputerScience
1
§ Problem:namingabunchofthingsCannotusevariables…willrunoutofnames!
§ Solu&onsTradi6onalapproach:name+index=arrayModernapproach:objectwithAPI=list,set,map
§ ComparisonArrayshavenoAPIandsufferfromfixedalloca6onThemoderncollec6onframeworkhasarichAPI
§ ButweoccasionallyusearraysForcompa6bilitywithlow-levelAPI(e.g.splitandargs)
2
§ Representacollec&onofen&&esofthesametype
§ Declara&on:type[]name;e.g.int[]bag;
§ Instan&a&on:newtype[size],e.g.bag=newint[100];
§ Refertoelementsbyname[index],e.g.bag[0]=123;bag[1]=bag[0]+5;
3
§ name.lengthrepresentsthearray’slength§ Indicesgofrom0tolength–1§ Mul&dimensionalarrayscanalsobeused
4
Collec&ons
EECS1022/Lespérance 2
Ifwepickanintegerin[1,1M]randomly,howlikelyisittogetonewhosedigitsumisdivisibleby7?
5
Computetheprobabilitybysampling10%ofthoseintegersandstorethesampleinacollec6on.
1. UseArraysSeeSumDiv7_array.java
2. UseCollec&onsSeeSumDiv7_coll.java
§ ListvsSetvsMapList:maycontainduplicatesandelementsareordered.Set:noduplicatesandnoorder.Map:key-valuepairs,keyunique.
§ TheInterfaces(akaAbstractDataTypes)List<E>,Set<E>,andMap<K,V>(usegenerics)
§ TheClasses(akaImplementa&ons)List:ArrayListandLinkedyList;Set:HashSetandTreeSetMap:HashMapandTreeMap
§ CommonAPIssize(),clear(),iterator(),toString()Methodstoinsert,delete,andsearchàCRUD
6
7
Basic
size()
clear()
iterator()
Map
put(K,V),get(K),keySet()
containsKey(K)
containsValue(V)
List/Set
add(E)
remove(E)
contains(E)
ListOnly
add(int,E)
remove(int)
get(int)
OtherAPI
Theenhancedforloop
Collec&ons.sort(List)
Arrays…seeAPI
§ add(Ee)onasetreturnsfalseifeisalreadyinit(foralistalwaysreturnstrue)
§ remove(Ee)returnstrueiffeisfoundinthesetorlist;foralistremovesonlyfirstoccurrence
§ Collec&ons.sort(List<E>l)rearrangesltomakeitsorted(accordingtonaturalorder)
§ Arrays.asList(E[]a)returnsaListrepresenta&onofarraya
8
Collec&ons
EECS1022/Lespérance 3
§ TraversingaList<E>bagi.e.goingthroughallofitselementsonebyone,isacommonopera&on:
for(Ee:bag){
System.out.println(e);
}
§ Similarlyforsets
§ Forlists,canalsodoanindexedtraversal:for(inti=0;i<bag.size();i++){
Ee=bag.get(i);System.out.println(e);
}
9
Givenalist,determinewhetheritcontainsduplicateelements.
Canbedonein3ways:
10
1. Sortthelistandthentraverseittocheckforadjacentduplicates
2. Createasetandthentrytoaddeachlistelementtoitcheckingifaddsucceeds
3. Traversethelist,andforeachelementtraversethelistagaintoseeifitoccurselsewhere
Collec&ons.sort(bag);
booleandis&nct=true;
for(inti=0;i<bag.size()-1;i++){
dis&nct=dis&nct&&!bag.get(i).equals(bag.get(i+1));
}
§ Canalsoexitassoonasaduplicateisfound:for(inti=0;i<bag.size()–1&&dis&nct;i++){
dis&nct=!bag.get(i).equals(bag.get(i+1));
}
11
Set<Integer>tmp=newHashSet<Integer>();
booleandis&nct=true;
for(inti=0;i<bag.size();i++){
dis&nct=dis&nct&&tmp.add(bag.get(i));
}
§ Canalsoexitassoonasaduplicateisfound:for(inti=0;i<bag.size()&&dis&nct;i++){
dis&nct=tmp.add(bag.get(i));
}
12
Collec&ons
EECS1022/Lespérance 4
booleandis&nct=true;
for(inti=0;i<bag.size();i++){
intx=bag.get(i);
for(intj=0;j<bag.size();j++){
inty=bag..get(j);
dis&nct=dis&nct&&(i=j||x!=y);
}
}Canalsoexitassoonasaduplicateisfoundbyadding&&dis&ncttobothloopcondi&ons
13
Iterator<Integer>outer=bag.iterator();
booleandis&nct=true;
while(outer.hasNext()&&dis&nct){
Integerx=outer.next();
Iterator<Integer>inner=bag.iterator();
while(inner.hasNext()&&dis&nct){
Integery=inner.next();
dis&nct=!x.equals(y)||x=y;
}
}
14
Givenalongsentence,findallitswords;thedis6nctones(regardlessofcase);displaythem;sortthem;andthenlocatethelongestandmostfrequentones.
15
A"word"isdefinedasasequenceofcharactersterminatedbyspace,punctua6on,orend-of-string.
1. Usesplitwitharegex2. Turnarraytoacollec&on3. Usecollec&onAPI
SeeWordSmith.java
§ Aniteratorisanobjectthatallowsyoutotraverseacollec&on
§ GivenareferencebagoftypeList<E>orSet<E>onecangetaniteratorforitasfollows:
Iterator<E>itr=bag.iterator();
§ Tocheckifthereisanextelementonecallsthebooleanmethoditr.hasNext()
§ Toobtainthenextelement(providedthereisone)wewrite
Ee=itr.next();
16
Collec&ons
EECS1022/Lespérance 5
TheextendedforloopforareferencebagoftypeList<E>orSet<E>:
for(Ee:bag){
…
}
justabbreviates/standsfor
for(Iterator<E>itr=bag.iterator();itr.hasNext();){
Ee=itr.next();
…
}
17
publicsta&cSet<E>intersect(Set<E>set1,Set<E>set2){
Set<E>result=newHashSet<E>();
for(Ee:set1){
if(set2.contains(e){
result.add(e);
}
}
returnresult;
} 18
publicsta&cSet<E>union(Set<E>set1,Set<E>set2){
Set<E>result=newHashSet<E>();
for(Ee:set1){
result.add(e);
}
for(Ee:set2){
result.add(e);
}
returnresult;
}
19 20
Basic
size()
clear()
iterator()
Map
put(K,V),get(K),keySet()
containsKey(K)
containsValue(V)
List/Set
add(E)
remove(E)
contains(E)
ListOnly
add(int,E)
remove(int)
get(int)
OtherAPI
Theenhancedforloop
Collec&ons.sort(List)
Arrays…seeAPI
Collec&ons
EECS1022/Lespérance 6
§ AMap<K,V>isrepresentsamappingbetweenasetofkeys(oftypeK)andasetofvalues(oftypeV)
§ Eachelementinamapisakey-valuepair
§ Thekeysmustformasetandallbedis&nct
§ Thereare2classesthatimplementtheinterfaceMap<K,V>:TreeMap<K,V>andHashMap<K,V>
§ Usemap.put(k,v)toaddorupdateakey-valuepair
§ Usemap.get(k)toretrievethevalueassociatedwithkeyk
§ Othermethods:remove(k,v),containsKey(k),containsValue(v),keySet(),size(),toString(),etc.
21
Map<String,Integer>m=newHashMap<String,Integer>();
m.put("John",23);
m.put("Mary",22);
m.put("Paul",19);
System.out.println("Maryis"+m.get("Mary"));
m.put("Mary",21);
System.out.println("Maryis"+m.get("Mary"));
22
Map<String,Integer>m=newHashMap<String,Integer>();
m.put("John",23);m.put("Mary",22);m.put("Paul",19);
for(Stringk:m.keySet()){
System.out.println(k+"is"+m.get(k));
}
23
Givenalongsentence,findallitswords;thedis6nctones(regardlessofcase);displaythem;sortthem;andthenlocatethelongestandmostfrequentones.
24
A"word"isdefinedasasequenceofcharactersterminatedbyspace,punctua6on,orend-of-string.
1. Usesplitwitharegex2. Turnarraytoacollec&on3. Usecollec&onAPI
SeeWordSmith.java
Collec&ons
EECS1022/Lespérance 7
§ SupposewewanttheinverseofaMap<K,V>m
§ Justtakingthesetofallpairsvalue-keysfrommdoesnotworkbecausethevaluesmaynotbeunique
§ Onesolu&onistocreateanewmapMap<V,List<K>>invwhichassociateseachvaluevinmtothelistofallthekeysthatmmapstov
§ E.g.inverseofthemap
{"John"=23,"Paul"=21,"Mary"=23}wouldthenbe{21=[”Paul"],23=["John","Mary"]}
25
publicsta&cMap<Integer,List<String>>invert_all(Map<String,Integer>map){
Map<Integer,List<String>>result=newTreeMap<Integer,List<String>>();
for(Stringk:map.keySet(){
intv=map.get(k);
if(!result.containsKey(v){
List<String>list=newArrayList<String>();
list.add(k);result.put(v,list);
}else{
List<String>exis&ng=result.get(v);
exis&ng.add(k);
}}
returnresult;
} 26
§ Addressesques&onssuchasHowmuch&me(orspace)doesagivenalgorithmtakedependingonthesizeoftheinput?
§ ThatisifNisthesizeoftheinput,andT(N)istherunning&meofthealgorithmforaninputofsizeN,wewanttoknowhowT(N)growsasNgrows
§ E.g.HowlongdoesittaketosortalistofsizeN?§ Running&memaydependontheactualinputvalue(e.g.
list);usuallywesimplifybylookingattheworstcase
27
§ Big-Onota&onisusedtocharacterizehowfasttherunning&meT(N)ofthealgorithmgrowsasthesizeoftheinputNgrows
§ T(N)isO(f(N))ifT(N)≤Cf(N)forallN≥KforsomeconstantsCandK
§ Thatis,ifT(N)isalwayslessthanf(N)mul&pliedbysomeconstantbeyondagivenvalueofN
28
Collec&ons
EECS1022/Lespérance 8
§ TofindoutifanelementxiscontainedinanunsortedList<Integer>listwecandoalinearsearch:
intresult=-1;booleanfound=false;
for(inti=0;i<list.size()&&!found;i++){
inte=list.get(i);
if(e==x){
result=i;found=true;
}
}
29
§ Thisisessen&allywhatthecontains()methoddoes
§ Therunning&meisO(N)whereNisthesizeforthelist
§ ThisisbecauseintheworstcasewehavetocheckandcomparealloftheNelementsofthelisttox
30
§ Tosearchasortedlist,thereisamuchfasteralgorithm,binarysearch,whichisusedbyCollec&ons.binarySearch(List<E>l,Ex)
§ Comparexwiththemiddleelementofthelist:ifitisequalwearedone,andifitislesswecaneliminateallelementsa{erit,andsimilarlyifitisgreater;thenrepeatwiththeremainingpartofthelist
§ Soa{ereachcomparisonwecutdowntheremainingpartofthelistbyhalf
§ Sotherunning&meisO(lgN)whereNisthesizeforthelist
31
§ Tosortalist,therearepre|yfastalgorithmssuchasquicksort,whichisusedbyCollec&ons.sort(List<E>l)
§ Therunning&meisO(NlgN)whereNisthesizeforthelist
32
Collec&ons
EECS1022/Lespérance 9
ArrayList§ get(int)andadd(E)areO(1)§ add(int,E),get(E),contains(E),remove(E),andremove(int)
areO(N)
LinkedList§ get(int)isO(N)§ add(0,E)isO(1)
33
TreeSet§ add(E)isO(lgN)§ contains(E)isO(lgN)§ remove(E)isO(lgN)
HashSet§ add(E)isO(1)§ contains(E)isO(1)§ remove(E)isO(1)
SimilarforTreeMapandHashMap
34