Set(HashSet、TreeSet)、泛型



一、set

Set:元素不可以重复,是无序。
Set接口中的方法和Collection一致。
      |--HashSet:内部数据结构是哈希表,是不同步的。
      |--TreeSet:可以对Set集合中的元素进行排序,是不同步的。

HashSet

       1.HashSet保证元素唯一性的方式 
                 HashSet通过元素的两个方法:hashCode()equals来完成,如果元素的hashCode值相同,才会判断equals是否为true,如果元素的hashCode值不同,不会调用equals

       2.存入到HashSet集合中的自定义对象,一般要复写hashCodeequals方法,这两个方法是集合底层自动调用的;


示例:


import java.util.*;

/*
	往hashSet集合中存入自定对象
	姓名和年龄相同为同一个人,重复元素。
*/
class HashSetTest 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
	public static void main(String[] args) 
	{
		HashSet hs =  new HashSet();
		hs.add(new Person("a1",11));
		hs.add(new Person("a2",12));
		hs.add(new Person("a2",12));
		hs.add(new Person("a3",13));

		sop("a1:"+hs.contains(new Person("a2",12)));

		Iterator it = hs.iterator();
		while(it.hasNext())
		{
			Person p = (Person)it.next();
			sop(p.getName()+"::"+p.getAge());
		}

	}
}

class Person
{
	private String name;
	private int age;
	Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public int hashCode()
	{
		System.out.println(this.name+"....hashCode");
		return name.hashCode()+age*39;
	}
	public boolean equals(Object obj)
	{
		
		if(!(obj instanceof Person))
		{
			return false;
		}
		Person p = (Person)obj;
		System.out.println(this.name+"...."+p.name);
		return this.name.equals(p.name) && this.age ==p.age;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}



哈希表确定元素是否相同
    

    1. 判断的是两个元素的哈希值是否相同。
       如果相同,再判断两个对象的内容是否相同。
    2. 判断哈希值相同,其实判断的是对象的HashCode方法。判断内容相同,用的是equals方法。

P.S.
    如果哈希值不同,不需要判断equals。


TreeSet

            1.TreeSet可以对set集合中的元素排序,底层数据结构是二叉树;

      2.TreeSet判断元素唯一性的方式:就是根据比较方法的返回结果是否是0,是0,就是相同元素,不存。


示例:


class  TreeSetDemo
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
	public static void main(String[] args) 
	{
			TreeSet ts = new TreeSet();

			ts.add(new Student("lisi02",22));
			ts.add(new Student("lisi007",20));
			ts.add(new Student("lisi09",19));
			ts.add(new Student("lisi01",19));

			Iterator it = ts.iterator();
			while(it.hasNext())
			{
				Student stu = (Student)it.next();
				sop(stu.getName()+"......"+stu.getAge());
			}

	}
}

class Student implements Comparable //该接口强制让学生具备比较性。
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public int compareTo(Object obj)
	{
		if(!(obj instanceof Student))
			throw new RuntimeException("不是学生对象");
		Student s = (Student)obj;

		System.out.println(this.name+"..compareto...."+s.name);
		if(this.age>s.age)
			return 1;
		if(this.age ==s.age)
			return this.name.compareTo(s.name);
		return -1;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}

TreeSet排序的第一种方式:

让元素自身具备比较性。
元素需要实现Comparable接口,覆盖compareTo方法、这种方式也称为元素的自然顺序,或者叫做默认顺序。

TreeSet的第二种排序方式:
当元素自身不具备比较性时,或者具备的比较性不是所需要时。
这时就需要让集合自身具备比较性。
在集合初始化时,就有了比较方式。

PS:

          当元素自身不具备比较性,或者具备的比较性不是所需要的。
          这时需要让容器自身具备比较性。
          定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
          当两种排序都存在时,以比较器为主。
          定义一个类,实现Comparator接口,覆盖compare方法。


示例:

import java.util.*;

class TreeSetDemo2
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
	public static void main(String[] args) 
	{
			TreeSet ts = new TreeSet(new MyCompare());

			ts.add(new Student("lisi02",22));
			ts.add(new Student("lisi007",20));
			ts.add(new Student("lisi09",19));
			ts.add(new Student("lisi01",18));
			ts.add(new Student("lisi01",20));

			Iterator it = ts.iterator();
			while(it.hasNext())
			{
				Student stu = (Student)it.next();
				sop(stu.getName()+"......"+stu.getAge());
			}

	}
}
class Student implements Comparable //该接口强制让学生具备比较性。
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public int compareTo(Object obj)
	{
		if(!(obj instanceof Student))
			throw new RuntimeException("不是学生对象");
		Student s = (Student)obj;

		//System.out.println(this.name+"..compareto...."+s.name);
		if(this.age>s.age)
			return 1;
		if(this.age ==s.age)
			return this.name.compareTo(s.name);
		return -1;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}
class MyCompare implements Comparator
{
	public int compare(Object o1,Object o2)
	{
		Student s1 = (Student)o1;
		Student s2 = (Student)o2;
		int num =  s1.getName().compareTo(s2.getName());

		if(num == 0)
		{
			if(s1.getAge()>s2.getAge())
				return 1;
			if(s1.getAge() == s2.getAge())
				return 0;
			
		}
		return -1;
	}
}


二、泛型

JDK1.5版本以后出现新特性。用于解决安全问题,是一个安全机制。


好处
      1.将运行时期出现的问题ClassCastException,转移到了编译时期。
         方便于程序员解决问题,让运行事情问题减少,安全,
      2.避免了强制转换麻烦。

泛型格式:通过<>来定义要操作的引用数据类型。

在使用java提供的对象时,什么时候写泛型呢?
        通常在集合框架中很常见。

        只要见到<>,就要定义泛型。
        其实<>就是用来接收类型的。
        当使用集合时,将集合中要存储的数据类型作为参数传递传递到<>即可。

示例:

import java.util.*;
class  GenericDemo
{
	public static void main(String[] args) 
	{
		
		ArrayList<String> a1 = new ArrayList<String>();

		a1.add("abc01");
		a1.add("abc01ss");
		a1.add("abc01dsfds");
		
		//a1.add(4);//a1.add(new Integer(4));

		Iterator<String> it  = a1.iterator();

		while(it.hasNext())
		{
			String s = it.next();

			System.out.println(s+":"+s.length());
		}
	}
}

泛型类


        1.类中要操作的引用数据类型不确定的时候,早起定义Object来完成扩展,现在定义泛型来完成扩展,例:

class Util<QQ>
{
    private QQ q;
    public void setObject(QQ q)
    {
        this.q=q;
    }
    public QQ getObject()
    {
        return q;
    }
}

        2.泛型类定义的泛型,在整个类中有效,如果被方法使用,那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了; 为了让不同方法可以操作不同类型,而且类型还不确定,那么可以将泛型定义在方法上,例:

class Demo<T>
{
    public void show(T t)
    {
        System.out.println("show:"+t);
    }
    public <Q> void print()
    {
        System.out.println("print:"+q);
    }
}

       3.特殊之处:
                  静态方法不可以访问类上定义的泛型。
                  如果静态方法操作的引用数据类型不确定,可以将泛型定义在方法上。

class Demo<T>
{
    public  void show(T t)
    {
        System.out.println("show:"+t);
    }
    public <Q> void print(Q q)
    {
        System.out.println("print:"+q);
    }
    public  static <W> void method(W t)
    {
        System.out.println("method:"+t);
    }
}
class GenericDemo4 
{
    public static void main(String[] args) 
    {
        Demo <String> d = new Demo<String>();
        d.show("haha");
        //d.show(4);
        d.print(5);
        d.print("hehe");
        Demo.method("hahahahha");
        /*
        Demo d = new Demo();
        d.show("haha");
        d.show(new Integer(4));
        d.print("heihei");
        Demo<Integer> d = new Demo<Integer>();
        d.show(new Integer(4));
        d.print("hah");
        Demo<String> d1 = new Demo<String>();
        d1.print("haha");
        d1.show(5);
        */
    }
}

        4.泛型定义在接口上

示例:

interface Inter<T>
{
	void show(T t);
} 

/*class InterImpl implements Inter<String>
{
	public void show(String t)
	{
		System.out.println("show:"+t);
	}
}
*/
class InterImpl<T> implements Inter<T>
{
	public void show(T t)
	{
		System.out.println("show:"+t);
	}
}
class  GenericDemo5
{
	public static void main(String[] args) 
	{
		InterImpl<Integer> i = new InterImpl<Integer>();
		i.show(4);
	}
}

         5.泛型的限定

                    泛型的限定:
                             ? extends E:可以接收E类型或者E的子类型。上限。
                             ? super E: 可以接收E类型或者E的父类型。

示例:

class  GenericDemo6
{
	public static void main(String[] args) 
	{
		/*
		ArrayList<String> a1 = new ArrayList<String>();

		a1.add("abc1");
		a1.add("abc2");
		a1.add("abc3");
		a1.add("abc4");

		ArrayList<Integer> a11 = new ArrayList<Integer>();
		a11.add(4);
		a11.add(7);
		a11.add(6);
		a11.add(8);
		
		printColl(a11);	
		printColl(a1);
		*/
		ArrayList<Person> a1  = new ArrayList<Person>();
		a1.add(new Person("abc1"));
		a1.add(new Person("abc2"));
		a1.add(new Person("abc3"));
		printColl(a1);

		ArrayList<Student> a11  = new ArrayList<Student>();
		a11.add(new Student("abc11"));
		a11.add(new Student("abc22"));
		a11.add(new Student("abc33"));
		printColl(a11);//ArrayList<String>a1 = new ArrayList<Person>();error

	}
	public static void printColl(ArrayList<? extends Person> a1)
	{
		Iterator<? extends Person> it = a1.iterator();//<?>占位符 ,不明确时
		while(it.hasNext())
		{
			System.out.println(it.next().getName());
		}
	}
	/*
	public static void printColl(ArrayList<?> a1)//ArrayList<String> a1 = new ArrayList<Integer>();error
	{
		Iterator<?> it = a1.iterator();//<?>占位符 ,不明确时
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}*/
}

class Person
{
	private String name;
	Person(String name)
	{
		this.name = name;
	}
	public String getName()
	{
		return name;
	}
}
class Student extends Person
{
	Student(String name)
	{
		super(name);
	}
}

class Student implements Comparable<Student>//<? super E>
{
	public int compareTo(Person s)
	{
		this.getName()	

	}
}

class Comp implements Comparator<Person>
{
	public int compare(Person s1, Person s2)
	{
		return s1.getName().compareTo(s2.getName());
	}
}	


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值