概念及实例见一下代码
1.Collection基础相关:
package com.atguigu.java_collection;
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接口:方法:①add(Object obj),addAll(Collection coll),size(),clear(),isEmpty();
* ②remove(Object obj),removeAll(Collection coll),retainAll(Collection coll),
* equals(Object obj),contain(Object obj),containAll(Collection coll),hashCode();
* ③iterator(),toArray();
* ------List接口:存储有序的,可以重复的元素("动态"数组)--新增的方法:删除remove(int index) 修改set(int index,Object obj)
* 获取get(init index) 插入add(int index,Object obj)
* 添加进List集合中的元素(或对象)所在的类一定要重写equals()方法
* ------ArrayList(主要的实现类)、LinkedList(对于频繁的插入、删除操作)、Vector(古老的实现类、线程安全的、效率低)
* ------Set接口:存储无序的,不可重复的元素(类似高中的"集合")
* ------HashSet、LinkedHashSet、TreeSet
*
* Map接口:存储"键-值"对的数据(函数y=f(x))
* key不可重复,使用set存放,value可以重复,使用Collection来存放。
* 一个key-value对构成一个entry(Map.Entry),entry使用set存放
* ------HashMap、LinkedHashMap、TreeMap、Hashtable(子类:Properties)
*/
public class TestCollection {
@Test
public void testCollection2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("aa");
coll.add(new Date());
coll.add("bb");
//6.contains(Object obj):判断集合中是否包含指定的obj元素,包含返回true,反之false
//判断依据:根据元素所在的类的equals()方法进行判断
//明确:如果存入集合中的元素是自定义的对象。要求:自定义类要求重写equals()方法
boolean b1 = coll.contains(123);
System.out.println(b1);
//7.containsAll(Collection coll):判断当前集合中是否包含coll中所有元素
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(new String("aa"));
boolean b2 = coll.containsAll(coll1);
System.out.println(b2);
// coll1.add(456);
//8.retainAll(Collection coll):求当前集合与coll的共有元素,返回给当前元素
// coll.retainAll(coll1);
// System.out.println(coll);
//9.remove(Object obj):删除集合中的obj元素。若删除成功返回true反之false
boolean b3 = coll.remove("cc");
System.out.println(b3);
//10.removeAll(Collection coll):从当前集合中删除包含在coll中的元素
coll.removeAll(coll1);
System.out.println(coll);
//11.equals(Object obj):判断两个集合元素是否完全一样
System.out.println(coll.equals(coll1));
//12.hashCode():
System.out.println(coll.hashCode());
System.out.println();
//13.toArray():将集合转成数组
Object[] obj = coll.toArray();
for(int i = 0;i < obj.length;i++){
System.out.println(obj[i]);
}
System.out.println();
//集合遍历
//14.iterator():返回一个Iterator接口实现类的对象
Iterator iterator = coll.iterator();
//方式一:不用
// System.out.println(iterator.next());
// System.out.println(iterator.next());
//方式二:不用
// for(int i = 0;i< coll.size();i++){
// System.out.println(iterator.next());
// }
//方式三:使用
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
@Test
public void testCollection1(){
Collection coll = new ArrayList();
//1.size():返回集合中元素的个数
System.out.println(coll.size());
//2.add(Object obj):向集合中添加一个元素
coll.add(123);
coll.add("aa");
coll.add(new Date());
coll.add("bb");
System.out.println(coll.size());
//3.addAll(Collection coll):将形参coll中包含的所有元素添加到当前集合中
Collection coll1 = Arrays.asList(1,2,3);
coll.addAll(coll1);
System.out.println(coll.size());
//查看集合元素
System.out.println(coll);
//4.isEmpty():判断集合是否为空
System.out.println(coll.isEmpty());
//5.clear():清空集合元素
coll.clear();
System.out.println(coll.isEmpty());
}
}
2.Iterator遍历以及增强For循环
package com.atguigu.java_collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.junit.Test;
public class TestIterator {
//使用增强for循环实现数组的遍历,注意数组没有迭代器
@Test
public void testFor1(){
String[] str = new String[]{"ss","dd","ff"};
for(String i:str){
System.out.println(i);
}
}
//使用增强for循环实现集合的遍历
@Test
public void testFor(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("aa");
coll.add(new Date());
coll.add("bb");
for(Object i:coll){
System.out.println(i);
}
}
//错误写法
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("aa");
coll.add(new Date());
coll.add("bb");
Iterator i = coll.iterator();
while((i.next()) != null){
System.out.println(i.next());
}
}
//正确写法:使用迭代器Iterator实现集合的遍历
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("aa");
coll.add(new Date());
coll.add("bb");
//iterator():返回一个Iterator接口实现类的对象
Iterator iterator = coll.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
3.List相关
package com.atguigu.java_collection;
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):在指定的索引位置index添加元素ele
boolean addAll(int index, Collection eles)
Object get(int index):获取指定索引的元素
Object remove(int index):删除指定索引位置的元素
Object set(int index, Object 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 ele))
查(get(int index)) 插(add(int index, Object ele)) 长度(size())
*/
@Test
public void testList2(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(new String("aa"));
list.add(new String("ss"));
list.add(456);
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
List list1 = list.subList(0, 3);//左闭右开
System.out.println(list1);
}
@Test
public void testList1(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(new String("aa"));
list.add(new String("ss"));
System.out.println(list);
list.add(0, 111);
System.out.println(list);
Object obj = list.get(1);
System.out.println(obj);
list.remove(0);
System.out.println(list.get(0));
list.set(0, 222);
System.out.println(list.get(0));
}
}
4.Set相关
先建Person、Customer两个类,set和map要用
Person类
package com.atguigu.java_collection;
public class Person implements Comparable{
private String name;
private Integer age;
public Person() {
super();
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = 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 [age=" + age + ", name=" + name + "]";
}
@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) {
if(o instanceof Person){
Person p = (Person)o;
return this.name.compareTo(p.name);
}
return 0;
}
}
Customer类:
package com.atguigu.java_collection;
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;
}
public Customer(String name, Integer id) {
super();
this.name = name;
this.id = id;
}
public Customer() {
super();
}
@Override
public String toString() {
return "Customer [name=" + name + ", 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;
}
}
Set相关
package com.atguigu.java_collection;
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 {
@Test
public void testTreeSet3() {
TreeSet set = new TreeSet(new Comparator() {
public int compare(Object o1, Object o2) {
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;
}
});
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 str : set) {
System.out.println(str);
}
}
/*
* 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) {
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 str : set) {
System.out.println(str);
}
}
/*
* 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("aa");
// set.add("ss");
// set.add("ff");
// set.add("kk");
// 当Person类没有实现Comparable接口时,当向TreeSet中添加Person对象时,报ClassCastException
set.add(new Person("cc",22));
set.add(new Person("ff",23));
set.add(new Person("aa",25));
for(Object str:set){
System.out.println(str);
}
}
/*
* LinkedHashSet:使用链表维护了一个添加进集合中的顺序,导致当遍历LinkedHashSet集合
* 元素时,是按照添加进去顺序遍历的!
*
* LinkedHashSet插入性能略低于 HashSet,但在迭代访问 Set 里的全部元素时有很好的性能。
*
*/
@Test
public void testLinkedHashSet(){
Set set = new LinkedHashSet();
set.add(123);
set.add(456);
set.add("aa");
set.add("ss");
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("aa");
//set.add("aa");
set.add("ss");
set.add(null);
Person p1 = new Person("gg", 25);
Person p2 = new Person("gg", 25);
set.add(p1);
set.add(p2);
System.out.println(set.size());
System.out.println(set);
}
}
5.Map相关
package com.atguigu.java_collection;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import org.junit.Test;
/*
* Collection接口
*
* Map接口:存储"键-值"对的数据(函数y=f(x))
* key不可重复,使用set存放,value可以重复,使用Collection来存放。
* 一个key-value对构成一个entry(Map.Entry),entry使用set存放
* |-----HashMap:Map的主要实现类
* |-----LinkedHashMap:使用链表维护添加进Map中的顺序。故遍历Map时,是按添加的顺序遍历的。
* |-----TreeMap:按照添加进Map中的元素的key的指定属性进行排序。要求:key必须是同一个类的对象!
* 针对key:自然排序 vs 定制排序
* |-----Hashtable:古老的实现类,线程安全,不建议使用。
* |----Properties:常用来处理属性文件。键和值都为String类型的
*/
public class TestMap {
//使用Properties处理属性文件
@Test
public void test6() throws FileNotFoundException, IOException{
Properties pros = new Properties();
pros.load(new FileInputStream(new File("jdbc.properties")));
String user = pros.getProperty("user");
System.out.println(user);
String password = pros.getProperty("password");
System.out.println(password);
}
// 定制排序
@Test
public void test5() {
Comparator com = new Comparator() {
public int compare(Object o1, Object o2) {
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;
}
};
TreeMap map = new TreeMap(com);
map.put(new Customer("AA", 1001), 87);
map.put(new Customer("CC", 1001), 67);
map.put(new Customer("MM", 1004), 77);
map.put(new Customer("GG", 1002), 97);
Set set1 = map.keySet();
for (Object obj : set1) {
System.out.println(obj + "----->" + map.get(obj));
}
}
// 自然排序
@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", 23), 99);
map.put(new Person("JJ", 13), 69);
Set set = map.keySet();
for(Object obj:set){
System.out.println(obj + "----->" + map.get(obj));
}
}
@Test
public void test3() {
Map map = new LinkedHashMap();
map.put("AA", 213);
map.put("BB", 45);
map.put(123, "CC");
map.put(null, null);
map.put(new Person("DD", 23), 89);
Set set1 = map.keySet();
for (Object obj : set1) {
System.out.println(obj + "----->" + map.get(obj));
}
}
/*
* 如何遍历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("DD",22), 656);
//1.遍历key集
Set set = map.keySet();
for(Object obj:set){
System.out.println(obj);
}
//2.遍历values集
Collection values = map.values();
Iterator i = values.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
//3.如何遍历key-value对
//方式一:
Set set1 = map.keySet();
for(Object obj:set1){
System.out.println(obj + "---->" + map.get(obj));
}
//方式二:
Set set2 = map.entrySet();
for(Object obj:set2){
Map.Entry entry = (Map.Entry)obj;
//System.out.println(entry.getKey() + "---->" +entry.getValue());
System.out.println(entry);
}
}
/*
* 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)
* boolean containsValue(Object 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", 45);
map.put(123, "CC");
map.put(null, null);
map.put(new Person("DD",22), 656);
map.put(new Person("DD",22), 565);
System.out.println(map.size());
System.out.println(map);
map.remove("BB");
System.out.println(map);
}
}
6.Collections:操作Collection和Map的工具类
package com.atguigu.java_collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
/*
* 操作Collection以及Map的工具类:Collections
*/
public class TestCollections {
/*
* Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
Object max(Collection,Comparator):根据 Comparator 指定的顺序,返回给定集合中的最大元素
Object min(Collection)
Object min(Collection,Comparator)
int frequency(Collection,Object):返回指定集合中指定元素的出现次数
void copy(List dest,List src):将src中的内容复制到dest中
boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换 List 对象的所有旧值
*/
@Test
public void testCollections2(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(12);
list.add(78);
list.add(456);
Object obj = Collections.max(list);
System.out.println(obj);
int count = Collections.frequency(list, 456);
System.out.println(count);
//实现List的复制
//List list1 = new ArrayList();//错误的实现方式
List list1 = Arrays.asList(new Object[list.size()]);
Collections.copy(list1, list);
System.out.println(list1);
//通过如下的方法保证list的线程安全性。
List list2 = Collections.synchronizedList(list);
System.out.println(list2);
}
/*
* reverse(List):反转 List 中元素的顺序
shuffle(List):对 List 集合元素进行随机排序
sort(List):根据元素的自然顺序对指定 List 集合元素按升序排序
sort(List,Comparator):根据指定的 Comparator 产生的顺序对 List 集合元素进行排序
swap(List,int, int):将指定 list 集合中的 i 处元素和 j 处元素进行交换
*/
@Test
public void testCollections1(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(12);
list.add(78);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
Collections.swap(list, 0, 1);
System.out.println(list);
}
}