Java---Set和Map基本实现

相关知识点

  1. 集合是一系列对象的聚集(Collection)
  2. java中提供了有关于集合的类库称为 Collection APL
  3. Collection APL 中的接口和类位于Java.util 包中,其基本的接口 Collection 和 Map
  4. collection 的子接口有两种 :set 和 list
    HashSet 和TreeSet 是实现Set接口的两个类
  5. Map 键-值集合 ( key-value)
    HashMap 和TreeMap 是实现Map接口的两个类
Set 的使用
boolean add(E e) 添加元素,但重复元素不会被添加成功
void clear() 清空集合
boolean contains(Object o) 判断 o 是否在集合中
Iterator iterator() 返回迭代器
boolean remove(Object o) 删除集合中的 o
boolean isEmpty( ) 判断是否为空
int size()元素个数
Set特点:(list的特点和Set刚好相反)
Set表示的是不重复元素的集合;
元素输入的顺序的输出的顺序没有关系;
相等的元素不会重复加入;
代码演示:
package collection;
import java.util.HashSet;
import java.util.Set;
public class TestHashSet {
		public static void main (String[] args) {
			Set h = new HashSet();
			h.add("1st");
			h.add("2nd");
			h.add("3rd");
			h.add("4th");
			h.add("5th");
			h.add("3rd");
			h.add(new Integer(9));
			System.out.println(h);
			System.out.println(h.contains(9));
			h.remove("3rd");
			System.out.println(h);
		}	
}
//运行结果
[1st, 3rd, 2nd, 4th, 5th, 9]
true
[1st, 2nd, 4th, 5th, 9]
Map 的使用
K getKey( ) 返回 entry 中的 key
V getValue( )  返回 entry 中的 value
V get(Object key) 返回 key 对应的 value
V getOrDefault(Object key, V defaultValue) 返回 key 对应的 value,key 不存在,返回默认值
V put(K key, V value) 设置 key 对应的 value
V remove(Object key) 删除 key 对应的映射关系
Set keySet() 返回所有 key 的不重复集合
Collection values() 返回所有 value 的可重复集合
Set> entrySet() 返回所有的 key-value 映射关系
boolean containsKey(Object key) 判断是否包含 key
boolean containsValue(Object value) 判断是否包含 value
package collection;
import java.util.HashMap;
import java.util.Map;
public class TestDemo {
     public static void main(String[] args) {
    	 Map<Integer,String> map = new HashMap<>() ;
    	 map.put(1,"hello") ;
    	 // key重复
    	 map.put(1,"Hello") ;
    	 map.put(3,"Java") ;
    	 map.put(2,"Bit") ;
    	 System.out.println(map) ;
    	 // 根据key取得value
    	 System.out.println(map.get(2));
    	 // 查找不到返回null
    	 System.out.println(map.get(99));
    	 System.out.println(map.isEmpty());
    	 System.out.println(map.size());
    	 System.out.println(map.keySet());//返回所有 key 的不重复集合
    	 System.out.println(map.remove(1));//删除
             System.out.println(map) ;
    	 System.out.println(map.containsKey(2));
    	 System.out.println(map.containsValue("Bit"));
     }
}
//运行结果
{1=Hello, 2=Bit, 3=Java}
Bit
null
false
3
[1, 2, 3]
Hello
{2=Bit, 3=Java}
true
true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值