JAVA基础知识-集合
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                JAVA基础知识-集合
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                文章目錄
- @[TOC](文章目錄)
 
- 集合
- Collection集合
- List集合
- ArrayList
- LinkedList
 
- Set集合
- HashSet
- TreeSet
 
 
- Map集合
- HashMap
 
- 迭代器
- Iterator
- ListIterator
 
- foreach
 
- Properties
- 小貼士
 
- @[TOC](文章目錄)
- Collection集合
- List集合
- ArrayList
- LinkedList
 
- Set集合
- HashSet
- TreeSet
 
 
- Map集合
- HashMap
 
- 迭代器
- Iterator
- ListIterator
 
- foreach
集合
Collection集合
add()方法用于添加元素get()方法,用于獲取某一下標(biāo)處的元素isEmpty()方法返回布爾類型,集合是否為空size()方法,返回集合的長度contains()方法,判斷集合中是否包含該元素containsAll()方法,判斷某一集合是否包含另一集合的所有元素remove()方法用于移除元素removeAll(),移除一個集合中包含另一個集合的所有元素indexOf()方法,返回某一元素首次出現(xiàn)的下標(biāo)lastIndexOf()方法,返回某一元素最后一次出現(xiàn)的下標(biāo)equals()方法,用于判斷兩集合中元素是否相同subList()方法,用于截取部分元素,得到新集合LinkedList中特有方法:addFirst()方法,添加元素到首位addLast()方法,添加元素到末位getFirst()方法,獲取首位元素getLast(),獲取末位元素removeFirst(),移除首位元素removeLast(),移除末位元素 public static void main(String[] args) {//創(chuàng)建Collection對象Collection<String> c1=new ArrayList();//ArrayList()底層封裝的是數(shù)組//集合中添加指定元素c1.add("路飛");c1.add("索隆");c1.add("娜美");c1.add("山治");System.out.println(c1);//移除集合中指定元素,返回布爾類型System.out.println(c1.remove("山治"));//trueSystem.out.println(c1.remove("烏索普"));//false//判斷集合是否為空,獲取集合元素個數(shù)System.out.println(c1.isEmpty());//falseSystem.out.println(c1.size());//3//判段是否包含指定元素System.out.println(c1.contains("娜美"));//trueSystem.out.println(c1.contains(""));//false//c1.clear();//清空元素System.out.println(c1);//[] }List集合
public static void main(String[] args) {//List是Collection接口的子接口,是一個有序的集合//創(chuàng)建List的對象List<String> list=new ArrayList();list.add("羅賓");list.add("烏索普");list.add("弗蘭奇");list.add("布魯克");//往指定位置添加元素list.add(0,"喬巴");list.add(2,"喬巴");list.add("喬巴");//不指定位置,則添加在最后System.out.println(list);//獲取指定下標(biāo)處的元素System.out.println(list.get(0));System.out.println(list.get(2));//刪除指定下標(biāo)出的元素,并返回該元素System.out.println(list.remove(0));//喬巴System.out.println(list);System.out.println(list.indexOf("喬巴"));//2System.out.println(list.lastIndexOf("喬巴"));//5System.out.println(list.lastIndexOf("托尼托尼·喬巴"));//-1,不存在System.out.println(list);//獲取集合中部分元素組成的新的集合List<String> list1=list.subList(1,5);//[1,5)System.out.println(list1);//[烏索普,喬巴,弗蘭奇,布魯克]//測試集合與集合之間的關(guān)系Collection<String> c2=new ArrayList();c2.add("羅賓");c2.add("甚平");System.out.println("c2="+c2);//c2=[羅賓,甚平]//判斷當(dāng)前集合是否包含另一個集合中的所有元素System.out.println("c1是否包含c2:"+c1.containsAll(c2));//c1是否包含c2:falseCollection<String> c3=new ArrayList();//將另一個集合中的所有元素添加到當(dāng)前集合中c3.addAll(c2);System.out.println(c3);//[羅賓,甚平]//判段兩個集合中的元素是否相同System.out.println(c3.equals(c2));//true}ArrayList
public class ArrayListDemo {public static void main(String[] args) {//創(chuàng)建ArrayList集合對象ArrayList<Student> list=new ArrayList();//創(chuàng)建學(xué)生對象Role r1=new Role("Luffy",19,"風(fēng)車村");Role r2=new Role("Zoro",21,"霜月村");Role r3=new Role("Nami",20,"可可亞西村");Role r4=new Role("Usopp",19,"西羅普村");//往集合添加元素list.add(r1);list.add(r2);list.add(r3);list.add(r4);//使用for循環(huán)遍歷集合for (int i = 0; i <list.size() ; i++) {System.out.println(list.get(i));//獲取指定下標(biāo)的元素}} } class Role{private String name;private int age;private String address;public Student() {}public Student(String name, int age, String address) {this.name = name;this.age = age;this.address = address;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';} }LinkedList
在存儲元素前,它會先創(chuàng)建一個節(jié)點對象,一個節(jié)點對象包括:前引用 元素 后引用。前引用指向前一個節(jié)點的后引用,第一個節(jié)點的前引用為null后引用指向后一個節(jié)點的前引用,最后一個節(jié)點的后引用為null public static void main(String[] args) {//創(chuàng)建LinkedList的對象實例LinkedList<String> list=new LinkedList();list.add("前進(jìn)梅利號");list.add("飛天梅利號");list.add("萬里陽光號");System.out.println(list);System.out.println("--------------(?′?`?)----------------");//測試特有方法list.addFirst("出發(fā)");list.addLast("嘻");System.out.println(list);//[出發(fā),前進(jìn)梅利號,飛天梅利號,萬里陽光號,嘻]System.out.println("--------------(?′?`?)----------------");System.out.println(list.getFirst());//出發(fā)System.out.println(list.getLast());//嘻System.out.println("--------------(?′?`?)----------------");System.out.println(list.removeFirst());System.out.println(list.removeLast());System.out.println(list);//[前進(jìn)梅利號,飛天梅利號,萬里陽光號]System.out.println("--------------(?′?`?)----------------");for (int i = 0; i <list.size() ; i++) {System.out.println(list.get(i));//獲取指定下標(biāo)的元素} }Set集合
set不包含重復(fù)元素,特點:沒有下標(biāo),不能通過索引獲取元素,元素是無序的,(存入和取出順序可能不同)元素不可以重復(fù)(包括null)set接口繼承父類接口Collection的方法引用HashSet
HashSet實現(xiàn)了Set接口,不允許重復(fù)元素,允許元素值為null,且只有一個,不保證元素順序擴(kuò)充容量,當(dāng)內(nèi)容占據(jù)0.75倍的內(nèi)存時,就會擴(kuò)充內(nèi)存為前內(nèi)存的2倍HashSet(int , float),元素,指定占據(jù)多少時擴(kuò)充 public static void main(String[] args) {//創(chuàng)建HashSet對象Set<String> hs1=new HashSet();//添加元素boolean b1=hs1.add("香克斯");hs1.add("路飛");hs1.add("巴基");boolean b2=hs1.add("巴基");System.out.println(hs1);//[香克斯, 路飛, 巴基]System.out.println("b1:"+b1);//b1:trueSystem.out.println("b2:"+b2);//b2:falseSystem.out.println("--------------(?′?`?)----------------");//測試是否為空,是否包含指定元素,集合大小System.out.println(hs1.isEmpty());//falseSystem.out.println(hs1.contains("路飛"));//trueSystem.out.println(hs1.size());//3System.out.println("--------------(?′?`?)----------------");//測試刪除指定元素System.out.println(hs1.remove("巴基"));//trueSystem.out.println(hs1.remove("巴基"));//falseSystem.out.println(hs1);//[香克斯,路飛]System.out.println("--------------(?′?`?)----------------");HashSet<String> hs2=new HashSet<>();hs2.add("喬拉可爾·米霍克");hs2.add("巴索羅米·熊");hs2.add("波雅·漢庫克");HashSet<String> hs3=new HashSet<>();hs3.add(" 波雅·漢庫克 ");hs3.add("卡普");hs3.add("戰(zhàn)國");System.out.println(hs2);//[喬拉可爾·米霍克,巴索羅米·熊,波雅·漢庫克]System.out.println(hs3);//[波雅·漢庫克,卡普,戰(zhàn)國]System.out.println(hs2.containsAll(hs3));//false,hs2沒有包含hs3的所有元素System.out.println("--------------(?′?`?)----------------");System.out.println(hs2.removeAll(hs3));//true,刪除hs2包含hs3中的元素System.out.println(hs2);//[喬拉可爾·米霍克,巴索羅米·熊]System.out.println(hs3);//[波雅·漢庫克,卡普,戰(zhàn)國]//for循環(huán)遍歷集合for (int i = 0; i <hs3.size() ; i++) {System.out.println(hs3.get(i));//獲取指定下標(biāo)的元素} } public static void main(String[] args) {HashSet<String> s=new HashSet<>();s.add(new String("龍"));s.add(new String("卡普"));s.add(new String("龍"));//重寫了HashCode()(根據(jù)內(nèi)容生成Hash值,內(nèi)容相同,Hash值相同)//重寫了equals()(根據(jù)內(nèi)容比較,內(nèi)容相同,比較結(jié)果也相同)System.out.println(s);//[龍,卡普]} //去重案例 public class AnLi {public static void main(String[] args) {HashSet<Role> s=new HashSet<>();Role s1=new Role("tom",19,"天津");Role s2=new Role("tom",19,"天津");Role s3=new Role("jack",20,"北京");Role s4=new Role("jack",20,"北京");s.add(s1);s.add(s2);s.add(s3);s.add(s4);//當(dāng)重寫HashCode()和equals()方法就會去重System.out.println(s);} } class Role{private String name;private String position;public Role(String name,String address) {this.name = name;this.position=position;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPosition() {return position;}public void setPosition(String position) {this.position=position;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Role role = (Role) o;return name.equals(role.name) &&position.equals(role.position);}@Overridepublic int hashCode() {return Objects.hash(name, position);}@Overridepublic String toString() {return "Role{" +"name='" + name + '\'' +", position='" + position + '\'' +'}';} }TreeSet
特點:不包含重復(fù)元素沒有索引可以將元素按照規(guī)則進(jìn)行排序空參構(gòu)造,類實現(xiàn)comparable,重寫comparator()有參構(gòu)造使用比較器排序,讓集合構(gòu)造重寫compareto() //TreeSet空參 public class TreeSetDemo {public static void main(String[] args) {/* TreeSet<Integer> s = new TreeSet<>();s.add(2);s.add(1);s.add(5);s.add(6);s.add(8);System.out.println(s);//[1, 2, 5, 6, 8],將元素進(jìn)行了排序*/TreeSet<Student> ts = new TreeSet<>();//空參構(gòu)造Student s1=new Student("艾斯",22);Student s2=new Student("薩博",22);Student s3=new Student("路飛",19);/*首先空參構(gòu)造,類實現(xiàn)comparable重寫comparator方法,后者調(diào)用該方法,this就指后者,如果返回值為負(fù)數(shù),后者存到左邊,先存入s1,再存s2,s2為后者 如果是正數(shù),后者存到右邊,存s3先和s1比,大則繼續(xù)往后比 如果是0,表示重復(fù),不存*/ts.add(s1);ts.add(s2);ts.add(s3);System.out.println(ts);//[Student{name='路飛', age=19}, Student{name='艾斯', age=22}, Student{name='薩博', age=22}]//底層將中文轉(zhuǎn)成拼音,在進(jìn)行排序,如果拼音相同,那么程序認(rèn)為重復(fù)} } class Student implements Comparable<Student>{private String name;private int age;@Overridepublic int compareTo(Student o) {/* //按照年齡進(jìn)行排序//只要年齡相同就會認(rèn)為是重復(fù),其他參數(shù)就不考慮int i= this.age-o.age;return i;*///此方法內(nèi),年齡為主判斷方法,姓名為次要判斷條件int i= this.age-o.age;//String類中有CompareTo()方法i = i==0 ? this.name.compareTo(o.getName()) : i;return i;}public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';} } //TreeSet有參 public class TreeSet1 {public static void main(String[] args) {TreeSet<Role> s=new TreeSet<>(new Comparator<Role>() {@Overridepublic int compare(Role o1, Role o2) {//o1表示要存入的元素,o2表示已經(jīng)存入集合的元素int result=o1.getAge()-o2.getAge();//判斷的主要條件result= result==0?o1.getName().compareTo(o2.getName()):result;//判斷的次要條件return result;}});Role t1=new Role("黃猿",58);Role t2=new Role("赤犬",55);Role t3=new Role("青雉",49);s.add(t1);s.add(t2);s.add(t3);System.out.println(s);} } class Role{private String name;private int age;public Role() {}public Role(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Role{" +"name='" + name + '\'' +", age=" + age +'}';} }Map集合
Map為雙列集合,每組元素都包括[key,value],為任意類型特點:key不允許重復(fù),再添加第二次已有的key時,value會被覆蓋通過key獲取value,key和value一對一元素是無序的遍歷Map需要先將其轉(zhuǎn)成EntrySet,再進(jìn)行遍歷方法:put()方法,用于添加元素get()方法,用于獲取元素remove()方法,用于移除元素size()方法,獲取集合的長度isEmpty()方法,返回布爾型,判斷集合是否為空containsKey()方法,判斷是否包含某個KeycontainsValue()方法,判斷是否包含某個ValuekeySet()方法,獲取集合中所有key組成的set集合values()方法,獲取集合中所有value組成的Collection集合entrySet()方法,獲取集合中[key-value]組成的set集合HashMap
HashMap是Map接口的實現(xiàn),底層是一個Entry數(shù)組 public static void main(String[] args) {//創(chuàng)建Map對象實例Map/*<String,String>*/ map=new HashMap<>() ;map.put("1",1);map.put("2",2);System.out.println(map);//指定泛型Map<String,String> map1=new HashMap<>() ;map1.put("羅賓","娜美");map1.put("索隆","山治");System.out.println(map1);System.out.println(map1.get("索隆"));//山治System.out.println(map1.remove("羅"));//nullSystem.out.println(map1);//{羅賓=娜美, 索隆=山治}System.out.println(map1.size());//2System.out.println(map1.isEmpty());//false//判斷集合中是否包含指定的key,指定的valueSystem.out.println(map1.containsKey("索隆"));//trueSystem.out.println(map1.containsValue("山治"));//true//獲取Map集合中所有key組成的set集合System.out.println(map1.keySet());//[羅賓, 索隆]//獲取Map集合中所有的value組成的Collection集合System.out.println(map1.values());//返回Map集合中key-value對兒組成的set集合//生成一個set集合泛型是map.entrySet<Map.Entry<String,String>> entires=map1.entrySet();System.out.println(map1.entrySet());//[羅賓=娜美, 索隆=山治]for (Map.Entry<String,String> m:entires) {System.out.println(m);}//生成set集合泛型為map.entryIterator<Map.Entry<String, String>> iterator = entires.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}} /*遍歷Map的方法:keySet()Collection values()Set EntrySet()*/ public static void main(String[] args) {Map<String,String> map=new HashMap<>() ;map.put("羅賓","娜美");map.put("索隆","山治");Set<String> set= map.keySet();for (String key:set) {System.out.println(key+""+map.get(key));}Collection<String> value=map.values();for (String v:value) {System.out.println(v);}Set<Map.Entry<String, String>> entrySet = map.entrySet();for (Map.Entry<String, String> e:entrySet) {System.out.println(e.getKey()+e.getValue());}}迭代器
Iterator
迭代器主要用于遍歷,且依賴于集合存在迭代器創(chuàng)建后,指針指向第一個元素上方調(diào)用hasNext()方法,判斷指針下方是否有元素,有則返回true調(diào)用Next()方法,將指針下移一位,并獲取當(dāng)前指針指向的元素 public static void main(String[] args) {//創(chuàng)建List的對象List<String> list=new ArrayList();list.add("我");list.add("是");list.add("甜");list.add("崽");//使用Iterator()方法獲取迭代器遍歷集合,Collection集合都可以使用這個迭代器Iterator<String> iterator=list.iterator();//獲取迭代器while(iterator.hasNext()){//判斷指針下方是否有元素,System.out.println(iterator.next());// 指針向下移動一位,打印元素}}ListIterator
ListIterator繼承了Iterator迭代器創(chuàng)建后,指針指向第一個元素上方調(diào)用hasNext()方法,判斷指針下方是否有元素,有則返回true調(diào)用Next()方法,將指針下移一位,在獲取當(dāng)前指針指向的元素previous()方法返回列表中的上一個元素hasPrevoius()方法如果在相反方向迭代具有更多元素,則返回true public static void main(String[] args) {//創(chuàng)建List的對象List<String> list=new ArrayList();list.add("我");list.add("是");list.add("甜");list.add("崽");//使用Iterator()方法獲取迭代器遍歷集合,Collection集合都可以使用這個迭代器ListIterator<String> listiterator=list.listIterator();while(listiterator.hasNext()){System.out.println(listiterator.next());}//反向遍歷list集合(先正向遍歷,在反向遍歷)while(listiterator.hasPrevious()){System.out.println(listiterator.previous());}}foreach
格式:for (數(shù)組數(shù)據(jù)類型或者泛型 變量名:數(shù)組名或者集合名) { }foreach:增強for循環(huán),簡易迭代器底層為迭代器與普通for循環(huán)的區(qū)別:無法獲取下標(biāo),不可以修改數(shù)組或集合中元素當(dāng)普通for循環(huán)修改元素時,修改的是堆內(nèi)存當(dāng)中的值 public static void main(String[] args) {//創(chuàng)建List的對象List<String> list=new ArrayList();list.add("我");list.add("是");list.add("甜");list.add("崽");for (String l:list) {System.out.println(l);}//使用普通for循環(huán)for (int i = 0; i <list.size() ; i++) {System.out.println(list.get(i));//獲取指定下標(biāo)的元素}}Properties
當(dāng)于Hashtable是一個Map體系的集合跟IO相關(guān)的方法沒有泛型,不需要尖括號只存字符串 public class PropertiesDemo {public static void main(String[] args) throws IOException {Map<String,String> map=new Hashtable();map.put("1","list");System.out.println(map.get("1"));Properties pro=new Properties();//增加元素pro.put("name","luffy");pro.put("age","19");System.out.println(pro);//{age=19, name=luffy}//刪除元素//pro.remove("age");//System.out.println(pro);//{name=luffy}//修改元素pro.put("age","20");//鍵不存在為添加,鍵存在為覆蓋System.out.println(pro);//{age=20, name=luffy}//查詢元素System.out.println(pro.get("name"));//遍歷Set<Object> ob = pro.keySet();for (Object key:ob) {System.out.println(key+":"+pro.get(key));}System.out.println("------");//所有鍵值對組成的對象Set<Map.Entry<Object, Object>> entries = pro.entrySet();for (Map.Entry<Object, Object> key:entries) {//Object value;System.out.println(key);}//方法(key,value)鍵和值必須是String類型Properties pro1=new Properties();pro1.setProperty("路飛","風(fēng)車村");pro1.setProperty("娜美","可可西亞村");System.out.println(pro1);System.out.println(pro1.getProperty("路飛"));System.out.println(pro1.stringPropertyNames());//IO//load():將指定文件中的鍵值對數(shù)據(jù)讀取到Properties集合中Properties pro2=new Properties();FileReader fr=new FileReader("a.properties");//調(diào)用load()方法完畢后,文件的數(shù)據(jù)就已經(jīng)在pro集合中了pro2.load(fr);fr.close();System.out.println(pro2);//Map為無序的,所以可能和文件中的順序不同//Store():將集合中的數(shù)據(jù)以鍵值對的形式保存到指定文件中pro2.setProperty("db1","123");pro2.setProperty("db2","1231");pro2.put("db3","12345");FileWriter fw=new FileWriter("a.properties");pro2.store(fw,null);//第二個參數(shù)為注釋fw.close();} }小貼士
集合中使用泛型,可以避免數(shù)據(jù)類型混亂集合長度是動態(tài)變化的,類型也是不定的ArrayList()集合數(shù)據(jù)存儲的結(jié)構(gòu)是數(shù)組結(jié)構(gòu),元素增刪慢,查找快LinkedList()底層結(jié)構(gòu)是鏈表,查詢元素慢,線程不安全,效率高,增刪元素快使用TreeSet需要制定排序規(guī)則總結(jié)
以上是生活随笔為你收集整理的JAVA基础知识-集合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: LightSwitch 社区内容汇总 –
- 下一篇: 面试官问我 “String 的不可变真的
