集合框架03-Set

本章内容

1. Set
  1.1 特点
  1.2 遍历
    1.2.1 foreach
    1.2.2 迭代器   
  1.3 常用实现类
      HashSet
      TreeSet
        自然比较接口: java.lang.Comparable 
        比较器: java.util.Comparaton


思维导图

 

Set

 特点:无序、对象不能重复

遍历 :1 foreach
            2 迭代器   

public static void main(String[] args) {
		
		//Set集合的特点:1.无序
		Set s = new HashSet();
		
		s.add("张三");
		s.add("李四");
		s.add("王五");
		s.add("赵六");
		
		//只有两种遍历方式 foreach
		for (Object object : s) {
			System.out.println(object);
		}
		
		System.out.println("---------------------------------------");
		
		//Set集合的特点:2.元素不能重复
		s.add("张三");
		
		for (Object object : s) {
			System.out.println(object);
		}
		
		System.out.println("---------------------------------------");
		
		//遍历方式  2.迭代器
		Iterator it = s.iterator();
		while(it.hasNext()) {
			Object next = it.next();
			System.out.println(next);
		}
	}

常用实现类

1.  HashSet

2. TreeSet  根据某种(规则)对里面的元素进行排序

public static void main(String[] args) {
		
		Set<String> set = new TreeSet<String>();
		//根据某种(规则)对里面的元素进行排序
		
		set.add("s");
		set.add("h");
		set.add("a");
		set.add("b");
		set.add("i");
		
		for (String string : set) {
			System.out.println(string);
		}
	}

  自然比较接口: java.lang.Comparable (实体类)

public int compareTo(User o) {
//		int i = this.getId()-o.getId();
		//大于0 顺序   小于0 倒序   等于0不会添加
		int i = this.getName().hashCode()-o.getName().hashCode();
		return i;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		return true;
	}

比较器: java.util.Comparaton

String以AscII码进行比较,返回差值

public class NameComparator implements Comparator<User> {

	@Override
	public int compare(User o1, User o2) {
		if(o1.getName().hashCode()-o2.getName().hashCode()>0) {
			return 100;
		} else if(o1.getName().hashCode()-o2.getName().hashCode()<0) {
			return -100;
		} else{
			return 0;
		}
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值