C++的STL里面专门有一个“集合”就是set;
Java里面也有Set,却只是集合的一种。
Java集合可分为Collection和Map两种体系
->Collection接口:
->Set:元素无序、不可重复的集合
->List:元素有序,可重复的集合(可以看成动态数组)
->Map接口:具有映射关系"key-value对"集合(key相当于函数的自变量,value相当于因变量)
15个重要方法,其中hashCode在后面Set中再详写,然后还有一个涉及泛型以后再说。
package com.mustso.java1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.junit.Test;
/*
* 1.存储对象可以考虑:①数组②集合
* 2.数组存储对象的特点:Student[] stu = new Student[20];stu[0] = new Student();...
* ->弊端:①一旦创建,其长度不可变。②真实的数组存放的对象的个数是不可知的。
* 3.集合
* Collection接口
* |-----List接口:存储有序的,可以重复的元素
* |-----ArrayList、LinkedList、Vector
* |-----Set接口:存储无序的,不可重复的元素
* |-----HashSet、LinkedHashSet、TreeSet
* Map接口:存储“键-值”对 的数据
* |-----HashMap、LinkedHashMap、TreeMap、Hashtable(子类:Properties)
*/
public class TestCollection {
@Test
public void testCollection1(){
Collection coll = new ArrayList();
//1.size():返回集合中元素的个数
System.out.println(coll.size());//0
//2.add(Object obj):向集合中添加一个元素
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
System.out.println(coll.size());//4
//3.addAll(Collection coll):将形参coll中包含的所有元素添加到当前集合中
Collection coll1 = Arrays.asList(1,2,3);
coll.addAll(coll1);
System.out.println(coll.size());//7
//查看集合元素
System.out.println(coll);
//4.isEmpty():
System.out.println(coll.isEmpty());//false
//5.clear():清空集合元素
coll.clear();
System.out.println(coll.isEmpty());//true
}
@Test
public void testCollection2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
// Person p = new Person("MM",23);
coll.add(new Person("MM",23));
System.out.println(coll);
//6.contains(Object obj):判断集合中是否包含指定元素,包含返回true
//判断的依据:根据元素所在的类的equals()方法判断
//明确:如果存入集合中的元素是自定义类的对象。要求:自定义类要重写equals()方法!
boolean b1 = coll.contains("AA");
System.out.println(b1);
boolean b2 = coll.contains(new Person("MM",23));
System.out.println(b2);
//7.containsAll(Collection coll):判断当前集合中是否包含coll中所有的元素
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add("AA");
boolean b3 = coll.containsAll(coll1);
System.out.println(b3);
coll1.add(456);
//8.retainAll(Collection coll):求当前集合与coll的共有元素,返回给当前集合
coll.retainAll(coll1);
System.out.println(coll);
//9.remove(Object obj):删除集合中的obj元素,若删除成功返回true否则返回false
boolean b4 = coll.remove("bb");
System.out.println(b4);
}
@Test
public void testCollection3(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM",23));
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add("AA");
//10.removeAll(Collection):从当前集合中删除包含在coll中的元素
coll.remove(coll1);
System.out.println(coll);
//11.equals(Object obj):判断两个集合中的所有元素是否完全相同
Collection coll2 = new ArrayList();
coll2.add(123);
coll2.add("AA");
System.out.println(coll1.equals(coll2));
//12.hashCode():
System.out.println(coll.hashCode());
//13.toArray():将集合转化为数组
Object[] obj = coll.toArray();
for (Object object : obj) {
System.out.println(object);
}
System.out.println("----------------------------------");
//14.iterator():返回一个Iterator接口实现类的对象,进而实现集合的遍历
Iterator iterator = coll.iterator();
//方式一:
// for (int i = 0;i < coll.size();++i){
// System.out.println(iterator.next());
// }
//方式二:推荐
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
testCollection3:
ArrayList是List接口下的主要实现类:
package com.mustso.java1;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class TestList {
/**
* ArrayList:List的主要实现类
* List中相对于Collection新增的方法:
* void add(int index,Object ele):在指定的索引位置添加元素ele
* boolean addAll(int index,Collection eles)
* Object get(int index):获取指定索引的元素
* Object remove(int index):删除指定索引位置的元素
* Object set(int index,Object ele):设置指定索引位置的元素为ele
* int indexOf(Object obj):返回obj在集合中首次出现的位置,没有的话返回-1
* int lastIndexOf(Object obj):返回obj在集合中最后一次出现的位置,没有的话返回-1
* List subList(int fromIndex,int toIndex):返回从fromIndex到toIndex结束的左闭右开的一个子list
*
* List常用的方法:
* ->增(add(Object obj))
* ->删(remove)
* ->改(set(int index,Object obj))
* ->查(get(int index))
* ->插(add(int index,Object ele))
* ->长度(size())
*
*/
@Test
public void testList1(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(new String("AA"));
list.add(new String("GG"));
System.out.println(list);
list.add(0, 555);//插入到头
System.out.println(list);
Object obj = list.get(1);//获取的是第二个元素123
System.out.println(obj);
list.remove(0);//删除头部元素
System.out.println(list.get(0));//输出头部元素:123
list.set(0, 111);//将头部元素设置为111
System.out.println(list.get(0));//输出头部元素:111
}
@Test
public void testList2(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(new String("AA"));
list.add(new String("GG"));
list.add(456);
//注意查找的时候是通过equals()方法比较
System.out.println(list.indexOf(456));//1
System.out.println(list.lastIndexOf(456));//4
System.out.println(list.indexOf(123)==list.lastIndexOf(123));//true
System.out.println(list.indexOf(444));//-1
System.out.println("-------------------------");
System.out.println(list);
List list1 = list.subList(0, 3);//复制 [0,3)的内容给list1
System.out.println(list1);
}
}
testList2()的运行结果:
顺便说说LinkedList和Vector
LinkedList的底层是拿链表实现的(而ArrayList底层是拿数组实现的),所以LinkedList方便做插入删除,对于频繁的插入删除操作优选LinkedList
Vector是古老的实现类了,是线程安全的,但是效率不高,基本不用了
HashSet是Set的主要实现类:
为了实现Set中的元素的不可重复性,特别值得强调的是hashCode()
当向Set中添加对象时,首先调用此对象所在类的hashCode()方法,计算此对象的哈希值,
此哈希值决定了此对象在Set中的存储位置。若此位置之前没有对象存储,则这个对象直接存储到此位置。
若此位置已有对象存储,再通过equals()方法比较这两个对象是否相同。
如果相同,后一个对象就不能再添加进来。
万一返回false呢,都存储。(不建议如此)
>要求:hashCode()方法要与equals()方法一致。
@Test
public void testHashSet(){
Set set = new HashSet();
set.add(123);
set.add(456);
set.add(new String("AA"));
set.add(new String("AA"));//不会添加进去
set.add("BB");
set.add(null);
Person p1 = new Person("GG",23);
Person p2 = new Person("GG",23);
System.out.println(p1.equals(p2));
set.add(p1);
set.add(p2);
System.out.println(set.size());
System.out.println(set);
System.out.println(set.size());
}
LinkedHashSet:使用链表维护了一个添加进集合中的顺序。
导致当我们遍历LinkedHashSet元素时是按照添加进去的顺序遍历的!
LinkedHashSet插入性能略低于HashSet,但在迭代访问Set里的全部元素时有很好的性能。
@Test
public void testLinkedHashSet(){
Set set = new LinkedHashSet();
set.add(123);
set.add(456);
set.add(new String("AA"));
set.add(new String("AA"));//不会添加进去
set.add("BB");
set.add(null);
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
TreeSet:
1.向TreeSet中添加的元素必须是同一个类的。
2.可以按照添加进集合中的元素的指定的顺序遍历。向String,包装类等默认按照从小到大的顺序遍历。
3.当向TreeSet中添加自定义的对象时,有两种方法:①自然排序②定制排序
4.自然排序:要求自定义类实现java.lang.Comparable接口并重写其compareTo(Object obj)
在此方法中,指明按照自定义类的哪个属性进行排序。
5.向TreeSet中添加元素时,首先按照compareTo()进行比较,一旦返回0,虽然仅是两个对象的此属性值相同
但是程序会认为这两个对象相同,进而后一个对象就不能添加进来。
>compareTo()与hashCode()以及equals()三者保持一致!
@Test
public void testTreeSet1(){
Set set = new TreeSet();
// set.add(new String("AA"));
// set.add(new String("AA"));//不会添加进去
// set.add("BB");
// set.add("JJ");
// set.add("GG");
// set.add("MM");
//当Person类没有实现Comparable接口时,当向TreeSet中添加Person对象时,报ClassCastException
set.add(new Person("CC",23));
set.add(new Person("MM",21));
set.add(new Person("GG",25));
set.add(new Person("JJ",24));
set.add(new Person("KK",20));
set.add(new Person("DD",20));
for (Object obj : set) {
System.out.println(obj);
}
}
运行结果:
TreeSet的定制排序:
compare()与hashCode()以及equals()三者保持一致!
@Test
public void testTreeSet2(){
//1.创建一个实现了Comparator接口的类对象
Comparator com = new Comparator(){
//向TreeSet中添加Customer类的对象,在此compare()方法中
//指明是按照Customer的哪个属性排序的。
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if (o1 instanceof Customer && o2 instanceof Customer ){
Customer c1 = (Customer)o1;
Customer c2 = (Customer)o2;
int i = c1.getId().compareTo(c2.getId());
if (i == 0){
return c1.getName().compareTo(c2.getName());
}
return i;
}
return 0;
}
};
//2.将此对象作为形参传递给TreeSet的构造器中
TreeSet set = new TreeSet(com);
//3.向TreeSet中添加Comparator接口中的compare方法中涉及的类的对象
set.add(new Customer("AA",1003));
set.add(new Customer("BB",1002));
set.add(new Customer("GG",1004));
set.add(new Customer("CC",1001));
set.add(new Customer("DD",1001));
for (Object obj : set) {
System.out.println(obj);
}
}
Person的实现:
package com.mustso.java1;
public class Person implements Comparable{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/*
* 当向TreeSet中添加Person类的对象时,依据此方法确定按照哪个属性排序。
*/
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
if (o instanceof Person){
Person p = (Person)o;
// return this.name.compareTo(p.name);
// return this.age.compareTo(p.age);//按年龄从小到大排
// return -this.age.compareTo(p.age);//按年龄从大到小排
int i = this.age.compareTo(p.age);
if (i == 0){
return this.name.compareTo(p.name);
}else{
return i;
}
}
return 0;
}
}
Customer的实现:
package com.mustso.java1;
public class Customer {
private String name;
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Customer [name=" + name + ", id=" + id + "]";
}
public Customer(String name, Integer id) {
super();
this.name = name;
this.id = id;
}
public Customer() {
super();
// TODO Auto-generated constructor stub
}
}
package com.mustso.java1;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Test;
/*
* Collection接口:
* |--------List接口:
* |-----ArrayList(主要实现类)
* |-----LinkedList(对于频繁的插入删除操作)
* |-----Vector(古老的实现类、线程安全、不常用)
* |--------Set接口:存储无序的,元素不可重复,Set中常用的方法都是Collection下定义的。
* |-----HashSet(主要实现类)
* |-----LinkedHashSet
* |-----TreeSet
*/
public class TestSet{
/*
* TreeSet的定制排序
*
* compare()与hashCode()以及equals()三者保持一致!
*/
@Test
public void testTreeSet2(){
//1.创建一个实现了Comparator接口的类对象
Comparator com = new Comparator(){
//向TreeSet中添加Customer类的对象,在此compare()方法中
//指明是按照Customer的哪个属性排序的。
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if (o1 instanceof Customer && o2 instanceof Customer ){
Customer c1 = (Customer)o1;
Customer c2 = (Customer)o2;
int i = c1.getId().compareTo(c2.getId());
if (i == 0){
return c1.getName().compareTo(c2.getName());
}
return i;
}
return 0;
}
};
//2.将此对象作为形参传递给TreeSet的构造器中
TreeSet set = new TreeSet(com);
//3.向TreeSet中添加Comparator接口中的compare方法中涉及的类的对象
set.add(new Customer("AA",1003));
set.add(new Customer("BB",1002));
set.add(new Customer("GG",1004));
set.add(new Customer("CC",1001));
set.add(new Customer("DD",1001));
for (Object obj : set) {
System.out.println(obj);
}
}
/*
* TreeSet:
* 1.向TreeSet中添加的元素必须是同一个类的。
* 2.可以按照添加进集合中的元素的指定的顺序遍历。向String,包装类等默认按照从小到大的顺序遍历。
* 3.当向TreeSet中添加自定义的对象时,有两种方法:①自然排序②定制排序
* 4.自然排序:要求自定义类实现java.lang.Comparable接口并重写其compareTo(Object obj)
* 在此方法中,指明按照自定义类的哪个属性进行排序。
* 5.向TreeSet中添加元素时,首先按照compareTo()进行比较,一旦返回0,虽然仅是两个对象的此属性值相同
* 但是程序会认为这两个对象相同,进而后一个对象就不能添加进来。
* >compareTo()与hashCode()以及equals()三者保持一致!
*
*/
@Test
public void testTreeSet1(){
Set set = new TreeSet();
// set.add(new String("AA"));
// set.add(new String("AA"));//不会添加进去
// set.add("BB");
// set.add("JJ");
// set.add("GG");
// set.add("MM");
//当Person类没有实现Comparable接口时,当向TreeSet中添加Person对象时,报ClassCastException
set.add(new Person("CC",23));
set.add(new Person("MM",21));
set.add(new Person("GG",25));
set.add(new Person("JJ",24));
set.add(new Person("KK",20));
set.add(new Person("DD",20));
for (Object obj : set) {
System.out.println(obj);
}
}
/*
* LinkedHashSet:使用链表维护了一个添加进集合中的顺序。
* 导致当我们遍历LinkedHashSet元素时是按照添加进去的顺序遍历的!
*
* LinkedHashSet插入性能略低于HashSet,但在迭代访问Set里的全部元素时有很好的性能。
*/
@Test
public void testLinkedHashSet(){
Set set = new LinkedHashSet();
set.add(123);
set.add(456);
set.add(new String("AA"));
set.add(new String("AA"));//不会添加进去
set.add("BB");
set.add(null);
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
/*
* Set:存储的元素是无序的、不可重复的!
* 1.无序性:无序性!=随机性。真正的无序性指的是元素在底层存储的位置无序。
* 2.不可重复性:当向Set中添加相同元素时,后面的这个不能添加进去
*
* 说明:要求添加进Set中的元素所在的类,一定要重写equals()和hashCode()方法
* 进而保证Set中元素的不可重复性
*
* Set中的元素是如何存储的呢?使用了哈希算法。
* 当向Set中添加对象时,首先调用此对象所在类的hashCode()方法,计算此对象的哈希值,
* 此哈希值决定了此对象在Set中的存储位置。若此位置之前没有对象存储,则这个对象直接存储到此位置。
* 若此位置已有对象存储,再通过equals()方法比较这两个对象是否相同。
* 如果相同,后一个对象就不能再添加进来。
* 万一返回false呢,都存储。(不建议如此)
* >要求:hashCode()方法要与equals()方法一致。
*/
@Test
public void testHashSet(){
Set set = new HashSet();
set.add(123);
set.add(456);
set.add(new String("AA"));
set.add(new String("AA"));//不会添加进去
set.add("BB");
set.add(null);
Person p1 = new Person("GG",23);
Person p2 = new Person("GG",23);
System.out.println(p1.equals(p2));
set.add(p1);
set.add(p2);
System.out.println(set.size());
System.out.println(set);
System.out.println(set.size());
}
}
package com.mustso.java1;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.junit.Test;
/*
* Collection接口
*
* Map接口
* |-----HashMap:Map的主要实现类
* |-----LinkedHashMap:使用链表维护添加进Map中的顺序,故遍历Map时是按照添加的顺序遍历的。
* |-----TreeMap:按照添加进Map中的元素的Key的指定属性进行排序
* 要求:key必须是同一个类的对象
* |-----Hashtable
* |-----Properties:
*/
public class TestMap {
/*
* Object put(Object key,Object value):向Map中添加一个元素
* Object remove(Object key):按照指定的key删除此key-value
* void putAll(Map t)
* void clear():清空
* Object get(Object key):获取指定key的value值.若无此key,返回null
* boolean containsKey(Object key):判断是否存在此key
* boolean containsValue(Object value):判断是否存在此value
* int size():返回集合的长度
* boolean isEmpty()
* boolean equals(Object obj)
*
* HashMap:
* 1.Key是用Set来存放的,不可重复。Value是用Collection存放的,可重复
* 一个key-value对,是一个Entry。所有的Entry是用Set存放的,也是不可重复的。
* 2.向HashMap中添加元素时,会调用key所在类的equals()方法,判断两个key是否相同。
* 若相同,则只添加后添加的那个元素。
*/
@Test
public void test1(){
Map map = new HashMap();
map.put("AA", 123);
map.put("BB", 456);
map.put("BB", 456);
map.put(123, "cc");
map.put(123, "dd");//将会取代上面一个
map.put(null, null);
System.out.println(map.size());
System.out.println(map);
map.remove("BB");
System.out.println(map);
Object value1 = map.get(123);
System.out.println(value1);
Object value2 = map.get(1234);//null
System.out.println(value2);
}
/*
* 如何遍历Map
* Set keySet()
* Collection values()
* Set entrySet()
*/
@Test
public void test2(){
Map map = new HashMap();
map.put("AA", 123);
map.put("BB", 456);
map.put(123, "cc");
map.put(null, null);
map.put(new Person("GG",27), 23);
//1.遍历key集
Set set = map.keySet();
for (Object object : set) {
System.out.println(object);
}
System.out.println();
//2.遍历value集
Collection values = map.values();
for (Object object : set) {
System.out.println(object);
}
System.out.println();
//3.如何遍历key-value对
Set set1 = map.entrySet();
for (Object object : set1) {
System.out.println(object);
}
// Set set1 = map.keySet();
// for (Object object : set1) {
// System.out.println(object + "--->"+map.get(object));
// }
}
@Test
public void test3(){
Map map = new LinkedHashMap();
map.put("AA", 123);
map.put("BB", 456);
map.put(123, "cc");
map.put(null, null);
map.put(new Person("GG",27), 23);
Set set = map.entrySet();
for (Object object : set) {
System.out.println(object);
}
}
@Test
public void test4(){
Map map = new TreeMap();
map.put(new Person("AA",23), 89);
map.put(new Person("MM",22), 79);
map.put(new Person("GG",33), 69);
map.put(new Person("JJ",13), 99);
Set set = map.keySet();
for (Object object : set) {
System.out.println(object);
}
}
}