国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

java中Map、Set、List的簡單使用教程(快速入門)

瀏覽:5日期:2022-08-18 13:43:05
Map、Set、List

java中Map、Set、List的簡單使用教程(快速入門)

List的常用方法

1、創(chuàng)建

List<Integer> list = new ArrayList<>(); List<Integer> list = new LinkedList<>(); //同時(shí)可以作為鏈表用List<List<Integer>> list = new ArrayList<>();

2、遍歷

//本質(zhì)上其實(shí)是調(diào)用Iteratorfor(String s:list){System.out.print(s);}

3、List轉(zhuǎn)化為數(shù)組

//兩種寫法都可以, 第一種微微規(guī)范一點(diǎn) , 但是只能是封裝類型的數(shù)組Integer array[] = list.toArray(new Integer[list.size()]);Integer array[] = list.toArray();//java8的寫法, 可以借助stream來實(shí)現(xiàn)直接轉(zhuǎn)化為 基本類型數(shù)組int[] result = list.stream().mapToInt(i->i).toArray();

4、數(shù)組轉(zhuǎn)化為List

//array[]是不是封裝類都無所謂, 不是封裝類型 系統(tǒng)會(huì)自動(dòng)轉(zhuǎn)換為封裝類型Integer array[] = {1,2,3};intarray[] = {1,2,3};List<Integer> list = new ArrayList<>(Arrays.asList(array));//由此有直接默認(rèn)給List賦值的簡便寫法List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

5、合并兩個(gè)List

List<Integer> list1 = new ArrayList<>();List<Integer> list2 = new ArrayList<>();list.addAll(list); //list2的元素全部加入list1Set的常用方法

1、創(chuàng)建Set

Set<String> set = new HashSet<>();Set<String> set = new TreeSet<>();

2、遍歷

for(Integer t:set){ System.out.print(t);}

3、數(shù)組轉(zhuǎn)Set

String[] strs = new String[]{'Tom', 'Bob', 'Jane'};Set<String> set = new HashSet<>(Arrays.asList(strs));

3、Set轉(zhuǎn)數(shù)組

String[] strs = new String[]{'Tom', 'Bob', 'Jane'};Set<String> set = new HashSet<>(Arrays.asList(strs));//同樣的也是封裝類型不能直接轉(zhuǎn)為 基本類型Object[] result = set.toArray();Map的常見用法

Map最大的特點(diǎn)就是以 key-value的方式才存儲(chǔ)數(shù)據(jù)

創(chuàng)建Map集合

Map<String,Integer> map = new HashMap<>(); //無序Map<String,Integer> map = new TreeMap<>(); //按key有序, 并可以實(shí)現(xiàn)自定義排序

遍歷Map集合

//通過索引遍歷, 效率不高for(String key:map.keySet()){Integer temp = map.get(key);}//通過entry遍歷 (推薦使用)for(Entry<String,Integer> entry: map.entrySet()){ String s = entry.getKey(); Integer a = entry.getValue();}

//獲取值map.get(object);map.getOrDefault(tmp, 0); //如果為空則設(shè)為0

注意事項(xiàng)

1、當(dāng)調(diào)用List的contains(Object o)方法時(shí)即使是相同內(nèi)容的對(duì)象,但不是相同對(duì)象會(huì)被判斷成不相同。需要手動(dòng)在對(duì)象中編寫equals方法,用Object.equals(a,b);

其余的常見方法均在圖片中給出。

總結(jié)

到此這篇關(guān)于java中Map、Set、List的簡單使用教程的文章就介紹到這了,更多相關(guān)java中Map、Set、List使用內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 司法| 彭州市| 天镇县| 南涧| 白山市| 平舆县| 南靖县| 都安| 博湖县| 鄯善县| 台山市| 博兴县| 崇州市| 凌海市| 兴隆县| 咸阳市| 如东县| 水城县| 宁乡县| 启东市| 贵港市| 靖州| 绥宁县| 丰宁| 鄂伦春自治旗| 新丰县| 拉孜县| 航空| 黄大仙区| 铜梁县| 澄城县| 莎车县| 鄂州市| 新乡市| 海盐县| 清水县| 邵阳县| 新邵县| 海口市| 宣武区| 齐齐哈尔市|