java集合框架collection(3)Set、List和Map
Set、List和Map是java collection中最常用的三种数据结构。
Set是集合,不允许有重复的元素,List是动态数组实现的列表,有序可重复,Map是key-value的键值对,用于快速存取。
Set的常用方法:
add() 插入元素
clear() 清空集合
contains() 是否包含某元素
equals() 是否和某对象完全相同
isEmpty() 是否为空
remove() 删除某元素
List常用方法:
add() 插入元素
clear() 清空集合
contains() 是否包含某元素
equals() 是否和某对象完全相同
isEmpty() 是否为空
remove() 删除某元素
get() 按照索引获取元素值
Map常用方法:
put(key,value) 增加新对象
containsKey() 是否包含key
containsValue() 是否包含value
keySet() 把key转为Set
Values() 把value转为List
package com.company; import java.util.*; /** * Created by wangbin10 on 2017/1/5. */ public class Collection { public static void main(String[] args){ //Set Set<Integer> s1 = new HashSet<Integer>(); for(int i=0;i<10;i++){ s1.add(i); } s1.remove(5); System.out.println(s1); System.out.println(s1.size()); System.out.println(s1.isEmpty()); //ArrayList List<String> s2=new ArrayList<String>(); s2.add("one"); s2.add("two"); s2.add("three"); s2.add("four"); s2.remove(0); System.out.println(s2.size()); System.out.println(s2.get(2)); System.out.println(s2.contains("two")); System.out.println(s2.equals(s2)); Iterator it=s2.iterator(); while(it.hasNext()){ System.out.println(it.next()); } //HashMap Map<String,Integer> s3=new HashMap<String, Integer>(); s3.put("zhao",1); s3.put("qian",2); s3.put("sun",3); s3.put("li",4); System.out.println(s3.get("sun")); System.out.println(s3.keySet()); System.out.println(s3.values()); System.out.println(s3.containsKey("wang")); System.out.println(s3.containsValue(5)); System.out.println(s3.remove("qian")); } }