JAVA 集合


首先是ArrayList  和 HashSet的对比

         ArrayList: 元素有序,可以重复,在这个有序集合里,每有一个对象就会放入一个引用,可能出现多个引用指向同一个对象的情况  HashSet 元素无序,不可重复,当放入对象时,首先查看里面是否有这样一个对象,如果有则bufang首先查看里面是否有这样一个对象,如果有,则不放,如果没有才会放入,如果真的很想放进去这个对象,除非将已经存在的对象删除。

hashcode的方法作用:
       理解:实现hashcode方法的HashSet集合要添加新的元素时,先要用这个元素的hashcode
方法,就立刻能定
位到它应该放置的位置上。如果这个位置上没有元素,它就直接存储在这个位置上,不用再进行任何比较了;如果个位置上已经有元素了,就调用它的equals方法与新元素比较,相同的话就不存在了,不相同就散列其它的地址上。

通常来说,一个类的两个实例对象用equals方法比较的结果相等时,它们的哈希码也必须相等,但反之则不成立,即equals方法比较结果不相等的对象可以有相同的哈希码,或者说哈希码相同的两个对象的equals方法比较的结果可以不等。当一个对象被存储进     HashSet集合中后,就不能修改这个对象中的那些参与计算哈希码的字段了,否则,对象修改后的哈希值与最初存储进HashSet集合中时哈希值就不同了在这种情况下,即使在contains方法使用该对象的当前引用作为的参数去HashSet集合中检索对象,将返回找不到对象的结果,这也导致无法从HashSet集合中单独删除当前对象,从而造成内存泄露。

package com.heima.cn;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;


public class TestRe {
	
	public static void main(String[] argc) {
		
		Child c1 = new Child(1, 3);
		Child c2 = new Child(2, 5);
		Child c3 = new Child(5, 3);
		Child c4 = new Child(1, 3);
		
		Collection collections1 = new ArrayList();
		Collection collections2 = new HashSet();
		collections1.add(c1);
		collections1.add(c2);
		collections1.add(c3);
		collections1.add(c4);
		
		System.out.println(collections1.size());
		
		collections2.add(c1);
		collections2.add(c2);
		collections2.add(c3);
		collections2.add(c4);
		System.out.println(collections2.size());
	}

}


public class Child {
	
	

	private int m;
	
	private int n;
	
	public Child(int m, int n) {
		this.m = m;
		this.n = n;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + m;
		result = prime * result + n;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Child other = (Child) obj;
		if (m != other.m)
			return false;
		if (n != other.n)
			return false;
		return true;
	}	
}



用反射来得到HashSet集合

	InputStream is = new FileInputStream("config.properties");
		Properties pro = new Properties();
		pro.load(is);
		is.close();
		String className = pro.getProperty("className");
		Collection collections1 = (Collection)Class.forName(className).newInstance();

config.properties文件

className=java.util.HashSet






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值