Collection是层次结构的根接口,表示一组对象。Collection中常用的集合子接口List和Set;
Collection中常用的方法:add(添加 )、clear(清除所有元素)、remove(删除)、contions(是否包含某个元素)size(集合中的元素数)、iterator(迭代出集合中的元素)、isEmpty(是否为空)、toArray(返回结合中元素的数组);
List集合中常用的实现类:ArrayList、LinkedList、Vector,List集合中的元素可以重复
List集合中的新方法:get(index返回指定位置上的元素)、indexOf("元素")返回元素第一次出现的下标、
lastIndexOf("元素")最后一次出现的位置,set(index,"元素")用指定元素替换知道那个位置上的元素。。
ArrayList:底层是数组结构;接口大小可变素组的是实现,允许包括null元素,此集合非同步的
LinkedList:底层是链表结构,允许null元素,此集合非同步的。提供了get、remove、add的first和last的方法
Vector:可以实现可增长的对象数组,是同步的
Set集合;常用的实现类:TreeSet和HashSet,Set集合中的元素不可以重复,
HashSet集合:底层是哈希表结构,此类允许使用null元素,此线程不同步;
TreeSet集合:底层是二叉数结构,基于TreeMap,,此此线程非同步
两种排序方式:1>让元素具备自身比较性,元素类需实现Comparable接口覆盖其compareTo方法
2>定义比较器(当两种方法都存在时,以比较器为主),定义一个类,实现Comparator接口覆盖其compar方法
什么时候使用比较器?当元素自身不具备比较器时,或者具备的比较器不是我们所需要时,这时需要让集合自身具备比较性
Map集合:该集合存储键值对,保证集合的唯一性;常用的实现类:Hashtable、HashMap、TreeMap;
常用的方法:clear(从此映射中一处映射关系)、get(key)获取键映射的值、put(key,value)添加元素
keySet方法和entrySet方法常用,用于获取集合中的键和值
Hashtable:此类实现一个哈希表,该哈希表将键映射到相应的值。任何非null对象都可以用作键或值,此类是同步的
HashMap:底层是哈希表结构,允许null值和null键,此类非同步
TreeMap:底层是二叉树结构,根据其键的自然顺序排序,此类是非同步的;
两种排序方式:1>让元素具备自身比较性,元素类需实现 Comparable接口覆盖其compareTo方法
2>定义比较器(当两种方法都存在时,以比较器为主),定义一个类,实现Comparator接口覆盖其compar方法
List、Map、Set三个接口,存取元素时,各有什么特点?
首先,List与Set具有相似性,它们都是单列元素的集合,所以,它们有一个功共同的父接口,叫Collection。Set里面不允许有重复的元素,所谓重复,即不能有两个相等(注意,不是仅仅是相同)的对象,即假设Set集合中有了一个A对象,现在我要向Set集合再存入一个B对象,但B对象与A对象equals相等,则B对象存储不进去,所以,Set集合的add方法有一个boolean的返回值,当集合中没有某个元素,此时add方法可成功加入该元素时,则返回true,当集合含有与某个元素equals相等的元素时,此时add方法无法加入该元素,返回结果为false。Set取元素时,没法说取第几个,只能以Iterator接口取得所有的元素,再逐一遍历各个元素。
List表示有先后顺序的集合,注意,不是那种按年龄、按大小、按价格之类的排序。当我们多次调用add(Obj e)方法时,每次加入的对象就像火车站买票有排队顺序一样,按先来后到的顺序排序。有时候,也可以插队,即调用add(int index,Obj e)方法,就可以指定当前对象在集合中的存放位置。一个对象可以被反复存储进List中,每调用一次add方法,这个对象就被插入进集合中一次,其实,并不是把这个对象本身存储进了集合中,而是在集合中用一个索引变量指向这个对象,当这个对象被add多次时,即相当于集合中有多个索引指向了这个对象,如图x所示。List除了可以以Iterator接口取得所有的元素,再逐一遍历各个元素之外,还可以调用get(index i)来明确说明取第几个。
Map与List和Set不同,它是双列的集合,其中有put方法,定义如下:put(obj key,objvalue),每次存储时,要存储一对key/value,不能存储重复的key,这个重复的规则也是按equals比较相等。取则可以根据key获得相应的value,即get(Object key)返回值为key所对应的value。另外,也可以获得所有的key的结合,还可以获得所有的value的结合,还可以获得key和value组合成的Map.Entry对象的集合。
List 以特定次序来持有元素,可有重复元素。Set无法拥有重复元素,内部排序。Map保存key-value值,value可多值。
集合和数组都可以存储对象,但有所不同
数组的长度是固定的,都是同一种类型;
集合的长度是可变的,可以存储不同类型的对象;
1.add方法的参数类型是object,以便与接收任意类型对象
2.集合中存储的都是对象的引用;
LinkedList 的特有方法
addFist(); addLast();
getFist(); getLast();获取元素但不删除元素
removeFirst(); removeLast();获取元素而且删除元素
LinkedList的举例
<strong><span style="font-size:18px;">public class LinkedListDemo {
public static void main(String[] args) {
LinkedList link = new LinkedList();
// link.addFirst("java1");
// link.addFirst("java2");
// link.addFirst("java3");
// link.addFirst("java4");
link.addLast("1");
link.addLast("2");
link.addLast("3");
link.addLast("4");
System.out.println(link);//打印集合
System.out.println(link.getFirst());//获取集合中第一个元素
System.out.println(link.getLast());//获取元素中最后一个元素
System.out.println(link.removeFirst());//获取集合中的第一个元素并删除
System.out.println(link);//删除第一个元素后打印
System.out.println(link.removeLast());//删除集合中的最后一个元素并删除
System.out.println(link);//删除最后一个后打印
}
}
</span></strong>
Set集合的特点:无序, 不可以重复元素
|--HashSet: 数据结构是哈希表,线程是非同步到
保证元素唯一性的原理,判断元素的hashCode的值是否相等
如果相同,还会继续判断equals方法,是否为true
|--TreeSet:可以对Set集合中的元素进行排序
TreeSet有两种排序方式:1>让元素自身具有比较性:即、元素需要实现Comparable接口,覆盖CompareTo方法;这种称为元素的自然顺序;
2>定义比较器:定义一个类,实现Comparator接口,覆盖Compare方法;
当两种方法都存在时以比较器为主;
TreeSet举例:
<strong><span style="font-size:18px;">public class Student implements Comparable{
private String name;
private int age;
public Student(){};
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name ;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
//第一种方式
//重写comparable接口的方法:按年龄大小排序
public int compareTo(Object obj) {
if(obj instanceof Student){
Student s = (Student)obj;
if(this.age > s.age){
return 1;
}else if(this.age == s.age){
return this.name.compareTo(s.name);
}else{
return -1;
}
}
return age;
}
}
//第二种方式
public class MyComparator implements Comparator{
//按输入顺序输出
public int compare(Object o1, Object o2) {
Student s1 = (Student)o1;
Student s2 = (Student)o2;
// return s1.getName().compareTo(s2.getName());//只比较姓名
//按输入顺序排序
int num = s1.getName().compareTo(s2.getName());
if(num == 0){//如果同名,按年龄大小排序
if(s1.getAge() > s2.getAge()){
return 1;
}else if(s1.getAge() == s2.getAge()){
return 0;
}else{
return -1;
}
}
return num;
}
}
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyComparator());
ts.add(new Student("张三",20));
ts.add(new Student("李四",22));
ts.add(new Student("王五",24));
ts.add(new Student("赵六",22));
ts.add(new Student("赵六",21));
//获取迭代器,取出集合中的元素
for(Iterator it = ts.iterator(); it.hasNext();){
Student s = (Student)it.next();//向下转型
System.out.println(s.getName() + "-->" + s.getAge());
}
}
}</span></strong>
TreeSet的小练习:以字符串的长短进行排序;
<strong><span style="font-size:18px;">import java.util.Comparator;
public class MyComparator implements Comparator{
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
// if(s1.length() > s2.length())
// return 1;
// if(s1.length() == s2.length())
// return 0;
//按数组的长度进行排序
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num == 0){//如果为0则按自然顺序排序
return s1.compareTo(s2);
}
return num;
}
}
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyComparator());
ts.add("abcd");
ts.add("cda");
ts.add("aaa");
ts.add("sd");
ts.add("hbcdf");
for(Iterator it = ts.iterator(); it.hasNext(); ){
System.out.println(it.next());
}
}
}
</span></strong>
带泛型的集合举例:
<strong><span style="font-size:18px;">import java.util.Comparator;
public class MyComparator implements Comparator<Person>{
public int compare(Person o1, Person o2) {
//int 部分是按年龄排序
// int num = new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
// if(num == 0){
//按输入顺序排序
return o1.getName().compareTo(o2.getName());
// }
// return num;
}
}
public class Person {
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
}
public class Student extends Person{
public Student(String name, int age) {
super(name,age);
}
}
public class Work extends Person{
public Work(String name, int age) {
super(name, age);
}
}
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>(new MyComparator());
ts.add(new Student("张三-->S",20));
ts.add(new Student("李四-->S",25));
ts.add(new Student("王五-->S",22));
ts.add(new Student("赵六-->S",24));
// for(Iterator<Student> it = ts.iterator(); it.hasNext();){
// Student s = it.next();
// System.out.println(s.getName() + "-->" + s.getAge());
// }
print(ts);
System.out.println("-----------------");
TreeSet<Work> tw = new TreeSet<Work>(new MyComparator());
tw.add(new Work("张三-->W",20));
tw.add(new Work("李四-->W",25));
tw.add(new Work("王五-->W",22));
tw.add(new Work("赵六-->W",24));
print(tw);
// for(Iterator<Work> it = tw.iterator(); it.hasNext();){
// Work w = it.next();
// System.out.println(w.getName() + "-->" + w.getAge());
// }
}
public static void print(Collection<? extends Person> c){
for(Iterator<? extends Person> it = c.iterator(); it.hasNext(); ){
Person p = it.next();
System.out.println(p.getName() + "-->" + p.getAge());
}
}
}</span></strong>
Map集合:该集合存储键值对,一对一对向里存,要保证键值对的唯一性
Map集合的三个子类:
|---Hashtable:底层是哈希表的数据结构,不可以存入null键和null值。该集合石线程同步的 JDK1.0.效率低
|---HashMap:底层是哈希表的数据结构,允许使用null键和null值,该集合石不同步的。JDK1.2.效率高
|---TreeMap:底层是二叉树河沟,线程不同步,可以用于给map集合中的键进行排序
Map集合的两种取出方式:keySet entrySet
取出原理:将map集合转成set集合,再通过迭代器取出
Map集合两种取出方式的举例:
<strong><span style="font-size:18px;">import java.util.Comparator;
public class MyComparator implements Comparator<Student>{
public int compare(Student s1, Student s2) {
//按年龄排序
int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if(num == 0){
return s1.getName().compareTo(s2.getName());
}
return num;
}
}
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(){};
public Student(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
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;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(Student s) {
int num = new Integer(this.age).compareTo(new Integer(s.getAge()));
if(num == 0){
return this.name.compareTo(s.getName());
}
return num;
}
}
public class StudentDemo {
/*
* 每个学生都有相应的归属地:
*学生:Student; 地址:String
*学生属性:姓名 年龄
*注意:姓名和年龄相同的视为同一个学生; 保证学生的唯一性;
*
*/
public static void main(String[] args) {
//HashMap集合不可以排序
// HashMap<Student,String> map = new HashMap<Student,String>();
//treeMap可以排序
TreeMap<Student,String> map = new TreeMap<Student,String>(new MyComparator());
map.put(new Student("d",20), "北京");
map.put(new Student("f",25), "上海");
map.put(new Student("a",23), "北京");
map.put(new Student("h",21), "天津");
map.put(new Student("r",19), "上海");
map.put(new Student("b",27), "广州");
System.out.println("-------------------Map.Entry方法------------------------");
//将映射关系存入Set集合
Set<Map.Entry<Student,String>> entrySet = map.entrySet();
//获取迭代器
for(Iterator<Map.Entry<Student,String>> it = entrySet.iterator(); it.hasNext(); ){
//取出映射关系
Map.Entry<Student, String> me = it.next();
//根据Map.Entry的get方法获取键和值
Student key = me.getKey();//获取键
String value = me.getValue();//获取值
System.out.println("姓名:" + key.getName() + " 年龄:" + key.getAge() + "--" + "地址:" + value);
}
System.out.println("----------------keySet方法---------------------");
//将Map集合中的键存入Set集合中
Set<Student> keySet = map.keySet();
//获取迭代器
for(Iterator<Student> it1 = keySet.iterator(); it1.hasNext(); ){
//获取所有的键
Student key = it1.next();
String value = map.get(key);
System.out.println("姓名:" + key.getName() + " 年龄:" + key.getAge()+ "-->" + "地址:" + value);
}
}
}</span></strong>
Map集合的扩展练习:
<strong><span style="font-size:18px;">public class Student {
private String name;
private int age;
public Student(String name, int age) {//有参构造
super();
this.name = name;
this.age = age;
}
public Student() {//无参构造
super();
// TODO Auto-generated constructor stub
}
public String getName() {//get方法
return name;
}
public void setName(String name) {//set方法
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {//hashCode方法
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {//equals方法
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
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() {//toString方法
return "Student [age=" + age + ", name=" + name + "]";
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class Demo {
/*
* 学校有两个班级, 班级里有学生(学生有姓名和年龄)
*/
public static void main(String[] args) {
//创建学校集合
HashMap<String,List<Student>> hm = new HashMap<String,List<Student>>();
//创建班的集合
List<Student> yure = new ArrayList<Student>();
//创建班的集合
List<Student> jiuye = new ArrayList<Student>();
yure.add(new Student("张三",23));
yure.add(new Student("李四",25));
yure.add(new Student("王五",22));
jiuye.add(new Student("赵六",21));
jiuye.add(new Student("田七",26));
jiuye.add(new Student("小刘",24));
hm.put("预热班", yure);
hm.put("就业班", jiuye);
// show(yure);
// show(jiuye);
print(hm);
}
public static void print(HashMap<String, List<Student>> hm){
//将Map集合键存入到Set集合中,并获取迭代器
for(Iterator<String> it = hm.keySet().iterator(); it.hasNext(); ){
String room = it.next();//获取班级名称
List<Student> stu = hm.get(room);//获取班级里的所有学生
System.out.println(room);//打印出班级
show(stu);//调用show方法,打印学生的姓名和年龄
}
}
public static void show(List<Student> list){
//获取迭代器
for(Iterator<Student> it = list.iterator(); it.hasNext(); ){
Student s = it.next();//获取所有学生
System.out.println("姓名:" + s.getName() +"-->"+ "年龄:" + s.getAge());
}
}
}
</span></strong>