------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
一 Set接口
Set是Collection子接口,Set接口中的方法和Collection中方法一致的。Set接口取出方式只有一种,迭代器。
注意:Set不循序包含重复的元素,也就是元素唯一。
|--HashSet:底层数据结构是哈希表,线程是不同步的。无序,高效;
|--LinkedHashSet:有序,hashset的子类。
|--TreeSet:对Set集合中的元素进行指定顺序的排序。不同步。TreeSet底层的数据结构就是二叉树。
1.HashSet
HashSet集合保证元素唯一性:通过元素的hashCode方法,和equals方法完成的。
当元素的hashCode值相同时,才继续判断元素的equals是否为true。
如果为true,那么视为相同元素,不存。如果为false,那么存储。
如果hashCode值不同,那么不判断equals,从而提高对象比较的速度。
注意:HashSet对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashCode和equals方法。
哈希表的原理:
1,对对象元素中的关键字(对象中的特有数据),进行哈希算法的运算,并得出一个具体的算法值,这个值 称为哈希值。
2,哈希值就是这个元素的位置。
3,如果哈希值出现冲突,再次判断这个关键字对应的对象是否相同。如果对象相同,就不存储,因为元素重复。如果对象不同,就存储,在原来对象的哈希值基础 +1顺延。
4,存储哈希值的结构,我们称为哈希表。
5,既然哈希表是根据哈希值存储的,为了提高效率,最好保证对象的关键字是唯一的。
这样可以尽量少的判断关键字对应的对象是否相同,提高了哈希表的操作效率。
对于ArrayList集合,判断元素是否存在,或者删元素底层依据都是equals方法。
对于HashSet集合,判断元素是否存在,或者删除元素,底层依据的是hashCode方法和equals方法。
Example:
import java.util.*;
class Person1 implements Comparable<Person1>
{
private String name;
private int age;
Person1(String name,int age)
{
this.name=name;
this.age=age;
}
public void setName(String name)
{
this.name=name;
}
public void setAge(int age)
{
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public boolean equals(Object obj)//复写equals()方法。
{
if(!(obj instanceof Person1))
{
throw new RuntimeException("不是学生对象");
}
else
{
Person1 p=(Person1)obj;
if(this.name.equals(p.name))
{
return this.age==p.age;
}
return this.name.equals(p.name);
}
}
public int hashCode()
{
return this.name.hashCode()+this.age*25;
}
public String toString()
{
return name+":"+age;
}
public int compareTo(Person1 p)
{
if(this.age>p.age)
{
return 1;
}
if(this.age==p.age)
{
return this.name.compareTo(p.name);
}
return -1;
}
public static void main(String[] args)
{
HashSet<Person1> hs=new HashSet<Person1>();//创建HashSet集合。
hs.add(new Person1("zhangsan",25));//添加元素。
hs.add(new Person1("zhangsan",25));
hs.add(new Person1("lisi",26));
hs.add(new Person1("lisi",26));
for(Iterator<Person1> it=hs.iterator();it.hasNext();)
{
Person1 p1=it.next();
System.out.println(p1.getName()+":"+p1.getAge());
}
}
}
2.TreeSet:
用于对Set集合进行元素的指定顺序排序,排序需要依据元素自身具备的比较性。
如果元素不具备比较性,在运行时会发生ClassCastException异常。
所以需要元素实现Comparable接口,强制让元素具备比较性,复写compareTo方法。
依据compareTo方法的返回值,确定元素在TreeSet数据结构中的位置。
TreeSet方法保证元素唯一性的方式:就是参考比较方法的结果是否为0,如果return 0,视为两个对象重复,不存。
注意:在进行比较时,如果判断元素不唯一,比如,同姓名,同年龄,才视为同一个人。
在判断时,需要分主要条件和次要条件,当主要条件相同时,再判断次要条件,按照次要条件排序。
TreeSet集合排序有两种方式,Comparable和Comparator区别:
1:让元素自身具备比较性,需要元素对象实现Comparable接口,覆盖compareTo方法。
2:让集合自身具备比较性,需要定义一个实现了Comparator接口的比较器,并覆盖compare方法,并将该类对象作为实际参数传递给TreeSet集合的构造函数。
第二种方式较为灵活。
Example:
//第一种方式:
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public void setName(String name)
{
this.name=name;
}
public void setAge(int age)
{
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public boolean equals(Object obj)//复写equals()方法。
{
if(!(obj instanceof Student))
{
throw new RuntimeException("不是学生对象");
}
else
{
Student p=(Student)obj;
if(this.name.equals(p.name))
{
return this.age==p.age;
}
return this.name.equals(p.name);
}
}
public int hashCode()
{
return this.name.hashCode()+this.age*25;
}
public String toString()
{
return name+":"+age;
}
public int compareTo(Student p)
{
if(this.age>p.age)
{
return 1;
}
if(this.age==p.age)
{
return this.name.compareTo(p.name);
}
return -1;
}
public static void main(String[] args)
{
TreeSet<Student> hs=new TreeSet<Student>();//创建HashSet集合。
hs.add(new Student("zhangsan",25));//添加元素。
hs.add(new Student("lisi",30));
hs.add(new Student("zhaowu",16));
hs.add(new Student("zhouqi",50));
for(Iterator<Student> it=hs.iterator();it.hasNext();)
{
Student p1=it.next();
System.out.println(p1.getName()+":"+p1.getAge());
}
//取出的顺序从小到大。
}
}
第二种方式:
import java.util.*;
class Student1
{
private String name;
private int age;
Student1(String name,int age)
{
this.name=name;
this.age=age;
}
public void setName(String name)
{
this.name=name;
}
public void setAge(int age)
{
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public boolean equals(Object obj)//复写equals()方法。
{
if(!(obj instanceof Student1))
{
throw new RuntimeException("不是学生对象");
}
else
{
Student1 p=(Student1)obj;
if(this.name.equals(p.name))
{
return this.age==p.age;
}
return this.name.equals(p.name);
}
}
public int hashCode()
{
return this.name.hashCode()+this.age*25;
}
public String toString()
{
return name+":"+age;
}
public static void main(String[] args)
{
TreeSet<Student1> ts=new TreeSet<Student1>(new Student1Comparator());//创建比较起对象作为参数传递给集合的构造函数。
ts.add(new Student1("zhangsan",25));//添加元素。
ts.add(new Student1("lisi",30));
ts.add(new Student1("zhaowu",16));
ts.add(new Student1("zhouqi",50));
for(Iterator<Student1> it=ts.iterator();it.hasNext();)
{
Student1 p1=it.next();
System.out.println(p1.getName()+":"+p1.getAge());
}
}
}
class Student1Comparator implements Comparator<Student1>
{
public int compare(Student1 s1,Student1 s2)
{
int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if(num==0)
{
return s1.getName().compareTo(s2.getName());
}
return num;
}
}
二 Map接口
Collection存储的是一个元素,Map存储的是一对元素。Map集合里存在两组值,一组是key,一组是value。Map里的key不允许重复。通过key总能找到唯一的value与之对应。
1.Map集合:
|--Hashtable:底层是哈希表数据结构,是线程同步的。不可以存储null键,null值。
|--HashMap:底层是哈希表数据结构,是线程不同步的。可以存储null键,null值。替代了Hashtable.
|--TreeMap:底层是二叉树结构,可以对map集合中的键进行指定顺序的排序。
Map集合存储和Collection有着很大不同:
Collection一次存一个元素;Map一次存一对元素。
Collection是单列集合;Map是双列集合。
Map中的存储的一对元素:一个是键,一个是值,键与值之间有对应(映射)关系。
特点:要保证map集合中键的唯一性。
2.Map常用方法:
1,添加。
put(key,value):当存储的键相同时,新的值会替换老的值,并将老值返回。如果键没有重复,返回null。
void putAll(Map);
2,删除。
void clear():清空
value remove(key) :删除指定键。
3,判断。
boolean isEmpty():
boolean containsKey(key):是否包含key
boolean containsValue(value) :是否包含value
4,取出。
int size():返回长度
value get(key) :通过指定键获取对应的值。如果返回null,可以判断该键不存在。当然有特殊情况,就是在hashmap集合中,是可以存储null键null值的。
Collection values():获取map集合中的所有的值。
5,想要获取map中的所有元素:
原理:map中是没有迭代器的,collection具备迭代器,只要将map集合转成Set集合,可以使用迭代器了。之所以转成set,是因为map集合具备着键的唯一性,其实set集合就来自于map,set集合底层其实用的就是map的方法。
3.Map 集合的两种取出方式
把map集合转成set集合:
方法:
Set keySet();将Map中所以的键存入到Set集合。因为Set具备迭代器。可以将map集合中的键都取出存放到set集合中。对set集合进行迭代。迭代完成,再通过get方法对获取到的键进行值的获取。
Set entrySet();//取的是键和值的映射关系。而这个关系的数据类型就是:Map.Entry
其实,Entry也是一个接口,它是Map接口中的一个内部接口。
Entry就是Map接口中的内部接口;
为什么要定义在map内部呢?entry是访问键值关系的入口,是map的入口,访问的是map中的键值对。
取出map集合中所有元素的方式一:keySet()方法。
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()) {
Object key = it.next();
Object value = map.get(key);
System.out.println(key+":"+value);
}
Example:
import java.util.*;
class MapDemo2
{
public static void main(String[] args)
{
HashMap<String,String> hm=new HashMap<String,String>();//创建HashMap集合
hm.put("张三","吉林");//添加元素。
hm.put("李四","黑龙江");
hm.put("王五","内蒙古");
hm.put("周七","山东");
Set<String> set=hm.keySet();//把Map集合转成Set集合。
for(Iterator<String> it=set.iterator();it.hasNext();)
{
String name=it.next();
System.out.println(name+"="+hm.get(name));
}
}
}
取出map集合中所有元素的方式二:entrySet()方法。
Set entrySet = map.entrySet();
Iterator it = entrySet.iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
System.out.println(me.getKey()+"::::"+me.getValue());
Example:
import java.util.*;
class MapDemo2
{
public static void main(String[] args)
{
HashMap<String,String> hm=new HashMap<String,String>();//创建HashMap集合
hm.put("张三","吉林");//添加元素。
hm.put("李四","黑龙江");
hm.put("王五","内蒙古");
hm.put("周七","山东");
Set<Map.Entry<String,String>> entrySet=hm.entrySet();
for(Iterator<Map.Entry<String,String>> it=entrySet.iterator();it.hasNext();)
{
Map.Entry me=it.next();
System.out.println(me.getKey()+"="+me.getValue());
}
}
}
Example:获取字符串中每个字母出现的次数。
/*
"kjhdfaskjhklh"-->a(1)d(1)...。
*/
import java.util.*;
class CharCountDemo
{
public static void main(String[] args)
{
String str="kjhdfaskjh~klh";
str=charCount(str);
System.out.println(str);
}
//定义一个方法统计字母出现的次数。
public static String charCount(String str)
{
char[] chr=str.toCharArray();//将字符串转成字符数组。
TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();//创建MAap集合.
int count=0;//定义计数器。
for(int x=0;x<chr.length;x++)
{
Integer value=tm.get(chr[x]);//获取集合中的值。
if(value!=null)
count=value;
count++;
tm.put(chr[x],count);//存入键值对。
count=0;
}
Set<Character> set=tm.keySet();
StringBuilder sb=new StringBuilder();//定义一个容器。
//遍历集合并存储到StringBuilder容器中。
for(Iterator<Character> it=set.iterator();it.hasNext();)
{
Character ch=it.next();
Integer value=tm.get(ch);
sb.append(ch+"("+value+")");
}
return sb.toString();
}
}