java 之 集合(hashSet)示例

来源:互联网 发布:家庭装修预算软件 编辑:程序博客网 时间:2024/06/08 19:51
import java.util.Collection;import java.util.HashSet;public class CollectionTest {/** * @param args */public static void main(String[] args) {Collection collections = new HashSet();ReflectPoint pt1 = new ReflectPoint(3, 3);ReflectPoint pt2 = new ReflectPoint(4, 4);ReflectPoint pt3 = new ReflectPoint(3, 3);collections.add(pt1);collections.add(pt2);collections.add(pt3);collections.add(pt1);//没有重写hashCode和equals, 输出3//都重写后 输出2//先根据哈希码存放,如果相等再去比较equals方法,不会重复add//去掉 hashCode  输出3, 哈希码根据内存地址来了,不一样,就不用equals了//重新加上hashCode方法,修改y值后,哈希码变了,在新的哈希码属于的区域找不到元素,就删除不了了//下边这行注释后,size就变为1,可以删掉pt1.y = 7;//还是2,删不掉,误以为删掉了,其实没有,这就会造成内存泄漏//删的时候,找不到pt1,存储区域改变了collections.remove(pt1);System.out.println(collections.size());}}

public class ArrayTest {/** * 相同的维数 * Arrays 工具类: * public static <T> List<T> asList(T... a) * 这是1.5的。如果参数是int[] 会把它当作一个对象,不会拆开输出 *  *  * public static List asList(Object[] a) * 这是1.4的。如果参数是String[],那么就会自动采用1.4的方法, * 参数符合,就会把数组中的元素拆开输出 *  * 不能得到数组(int[] a)的类型,只能得到某个元素的类型 * a[0].getClass().getName(); *  * Object[] a = new Object[]{"a",1}; * @param args */public static void main(String[] args) {int[] a1 = new int[3];int[] a2 = new int[4];int[][] a3 = new int[2][3];String[] a4 = new String[3];//是不是同一份字节码System.out.println(a1.getClass()==a2.getClass());//下边两句编译通不过//System.out.println(a1.getClass()==a4.getClass());//System.out.println(a1.getClass()==a3.getClass());//[I 大写I 代表intSystem.out.println(a1.getClass().getName());//java.lang.ObjectSystem.out.println(a1.getClass().getSuperclass().getName());}}


原创粉丝点击