栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

集合框架03-Set

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

集合框架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 set = new TreeSet();
		//根据某种(规则)对里面的元素进行排序
		
		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 {

	@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;
		}
	}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914902.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号