Map与Set集合

一、Set集合的特点Set集合的特点:  无序(存储和读取的顺序有可能不一样);  不允许重复(要求元素唯一);  没有索引。利用HashSet存储字符串并遍历(三种遍历方法): public static void main(String[] args) { //创建集合对象 Set<String> set = new HashSet<Strin...
摘要由CSDN通过智能技术生成

一、Set集合的特点
Set集合的特点:
  无序(存储和读取的顺序有可能不一样);
  不允许重复(要求元素唯一);
  没有索引。
利用HashSet存储字符串并遍历(三种遍历方法):

	public static void main(String[] args) {
   
		//创建集合对象
        Set<String> set = new HashSet<String>();

        //添加元素
        set.add("hello");
        set.add("world");
        set.add("bupt");
        
        //遍历集合对象(分为三种:数组遍历、迭代器遍历、增强for循环)
        
        //数组遍历
        Object[] objs = set.toArray();
        for(int i=0; i < objs.length; i++) {
   
        	System.out.println(objs[i]);
        }
        
        //迭代器遍历
        Iterator<String> it = set.iterator();
        while(it.hasNext()) {
   
        	System.out.println(it.next());
        }
        
        //增强for循环遍历
        for(String s : set){
   
        	System.out.println(s);
        	
        }
      
	}

二、HashSet存储自定义对象并遍历
通过查看源码发现
  HashSet的add方法会使用当前集合中的每一个元素的Hash值与新添加元素的Hash值进行比较:如果Hash值(通过hashCode方法获取)不一样,则直接添加新的元素;如果Hash值一样,则比较比较地址值或者使用元素中重写的equals方法进行比较,若比较结果一样,则认为元素重复,不再添加,若比较结果不一样,则可以添加。

public class test {
   	
	public static void main(String[] args) {
   
		//创建集合对象
        HashSet<Student> set = new HashSet<Student>();

        //创建自定义类对象
        Student s0 = new Student("hxf2",20);
        Student s1 = new Student("hxf",18);
        Student s2 = new Student("hxf1",19);
        Student s3 = new Student("hxf2",20);
        
        //将自定义类对象添加到集合中
        set.add(s1);
        set.add(s2);
        set.add(s3);

        for(Student s : set){
        //增强for循环遍历集合
        	System.out.println(s);
        	System.out.println(s.hashCode());
        	
        }  
	}	
}
	
class Student{
   
	private String name;
	private int age;
	
	public Student(String name, int age) {
      //构造方法,为了初始化
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
      //使用Eclipse自动生成,用于显示自定义类Student的成员变量
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
	&#
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值