1.Java集合框架概述
Java集合框架关系如图,其中Collection和Map同样是集合的顶级。
2.List集合
List集合代表一个元素有序,可重复的集合,集合中的每个元素都有其对应的顺序索引。
常用实现类:ArrayList LinkedList
遍历方式:for循环,Iterator
ArrayList 内部以数组的形式来保存集合中的元素,线程不安全;通常用for循环遍历。Vector线程安全,但Vector是个古老的类,存在很多缺点。
示例:
- public class ArrayLsitDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ArrayList<String> arr = new ArrayList<String>();
- //增
- arr.add("菠萝");
- arr.add("香蕉");
- arr.add("李子");
- print(arr);
- //删
- arr.remove(0);//根据索引删除,引用对象知识移除地址
- print(arr);
- //改
- arr.set(1, "橙子");
- print(arr);
- //查
- System.out.println(arr.get(0));
- }
- //遍历
- public static void print(ArrayList<String> arr){
- for(String str:arr){
- System.out.print(str + " ");
- }
- System.out.println();
- }
- }
运行结果:
LinkedList可以根据索引来访问集合中的元素,此外还实现了Deque接口,所以也可以当成双端队列来使用,即可当“栈”(先进后出),也可以当作队(先进先出);内部是以线性表和链表实现的,保证输入的顺序。通常用Iterator遍历。
示例:
- public class LinkedListDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- LinkedList<String> list = new LinkedList<String>();
- list.add("哈哈");
- list.add("呵呵");
- list.add("嘿嘿");
- print(list);
- list.addFirst("嘻嘻");//链表可以在头或尾插入
- print(list);
- //将元素加入到对头
- list.offerFirst("来来");
- //将元素加入到队尾
- list.offerLast("去去");
- print(list);
- //访问并不删除栈顶
- System.out.println("访问并不删除栈顶----" +list.peekFirst());
- print(list);
- //访问并删除栈顶
- System.out.println("访问并删除栈顶----" + list.poll());
- print(list);
- }
- public static void print(List list){
- Iterator iterator = list.iterator();
- while(iterator.hasNext()){
- System.out.print(iterator.next() + " ");
- }
- System.out.println();
- }
- }
运行结果:
注意:LinkedList在进行删除、插入操作时性能更优,而ArrayList在遍历的时候应能更优。
3.Set集合
Set集合不循序包含相同的元素。
常用实现类:HashSet LinkedHashSet TreeSet
遍历方法:Iterator
HashSet通过equals() 和hashCode()方法来判断两个元素是否相等,不保证元素的输入顺序
示例:
- public class HashSetDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- HashSet<String> set = new HashSet<String>();
- //增
- set.add("小猫");
- set.add("小狗");
- set.add("小猪");
- System.out.println(set.add("小猫"));//返回false,不能重复添加
- print(set);
- //添加自定义对象,需重写hashCode() 和equals()方法
- HashSet<Dog> dogs = new HashSet<Dog>();
- dogs.add(new Dog("ho",1));
- dogs.add(new Dog("wo",3));
- dogs.add(new Dog("1o",2));
- System.out.println(dogs.add(new Dog("1o",2)));//无法添加相同对象
- print(dogs);
- }
- public static void print(Set set){
- Iterator i = set.iterator();
- while(i.hasNext()){
- System.out.print(i.next());
- System.out.print(" ");
- }
- System.out.println();
- }
- }
- class Dog{
- private String name;
- private int age;
- public Dog(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @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;
- Dog other = (Dog) 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() {
- return "Dog [name=" + name + ", age=" + age + "]";
- }
- }
运行结果:
LinkedSet 保证元素的输入顺序
示例:
- public class LinkedSetDemo {
- public static void main(String[] args) {
- LinkedHashSet<String> set = new LinkedHashSet<String>();
- set.add("第一");
- set.add("第二");
- set.add("第三");
- set.add("第四");
- set.add("胜利");
- Iterator<String> i = set.iterator();
- while(i.hasNext()){
- System.out.println(i.next());
- }
- }
- }
运行结果:
TreeSet是通过自然排序或者自定义排序来保存元素的
自然排序
示例:
- public class TreeSetDemo {
- public static void main(String[] args) {
- //添加自定义元素,需重写compareTo方法
- TreeSet<Man> man = new TreeSet<Man>();
- man.add(new Man("小白", 14));
- man.add(new Man("小白", 14));//同名同姓的表示同一个热闹
- man.add(new Man("小白", 15));
- man.add(new Man("小白", 16));
- man.add(new Man("小白", 17));
- print(man);
- }
- public static void print(Set set){
- Iterator i = set.iterator();
- while(i.hasNext()){
- System.out.print(i.next());
- System.out.print(" ");
- }
- System.out.println("打印完毕!");
- }
- }
- class Man implements Comparable<Man>{
- private String name;
- private int age;
- public Man(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @Override
- public String toString() {
- return "Man [name=" + name + ", age=" + age + "]";
- }
- @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;
- Man other = (Man) 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(Man o) {
- if(this.age > o.age){
- return 1;
- }else if(this.age < o.age){
- return -1;
- }
- return 0;
- }
- }
运行结果:
自定义排序
示例:
- public class TreeSetDemo {
- public static void main(String[] args) {
- //自定义比较器,传入匿名内部类 Comparator
- TreeSet<Man> man = new TreeSet<Man>(new Comparator<Man>() {
- public int compare(Man o1, Man o2) {
- if(o1.getAge()> o2.getAge()){
- return 1;
- }else if(o1.getAge() < o2.getAge()){
- return -1;
- }
- return 0;
- }
- });
- man.add(new Man("小白", 14));
- man.add(new Man("小白", 14));//同名同姓的表示同一个热闹
- man.add(new Man("小白", 15));
- man.add(new Man("小白", 16));
- man.add(new Man("小白", 17));
- print(man);
- }
- public static void print(Set set){
- Iterator i = set.iterator();
- while(i.hasNext()){
- System.out.print(i.next());
- System.out.print(" ");
- }
- System.out.println("打印完毕!");
- }
- }
- class Man {
- private String name;
- private int 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;
- }
- public Man(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @Override
- public String toString() {
- return "Man [name=" + name + ", age=" + age + "]";
- }
- @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;
- Man other = (Man) 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;
- }
- }
运行结果:
4.Map集合
Map是用于保存具有映射关系的数据,有两组值,一组值是用来保存Map里的Key,另外一组值是用来保存Map里的value。key不允许重复。
常用实现类:HashMap LinkedHashMap TreeMap
遍历方法有两种:keySet() entrySet()
1)HashMap线程不安全,允许null作为key,HashTable线程安全,但是古老少用,不允许null作为key。
示例:
- public class HashMapDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- HashMap<Integer, String> map = new HashMap<Integer,String>();
- map.put(12, "吃饭");
- map.put(14, "睡觉");
- map.put(13, "打豆豆");
- //第一种遍历方式keySet()
- Set<Integer> keySet = map.keySet();
- Iterator<Integer> i = keySet.iterator();
- while(i.hasNext()){
- Integer key = i.next();
- System.out.println("键是:" + key + "值是:" + map.get(key));
- }
- System.out.println("*******************************");
- //第二种遍历方式entrySet()
- Set<Entry<Integer,String>> entrySet = map.entrySet();
- Iterator<Entry<Integer, String>> iterator = entrySet.iterator();
- while(iterator.hasNext()){
- Entry<Integer, String> next = iterator.next();
- System.out.println("键是:" + next.getKey() + "值是:" + next.getValue());
- }
- }
- }
2)LinkedHashMap
LinkedHashMap也是使用双向链表来维护key-value,保证迭代顺序与key-value对的插入顺序一直。
示例:
- public class LinkedHashMapDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer,String>();
- map.put(12, "吃饭");
- map.put(14, "睡觉");
- map.put(13, "打豆豆");
- map.put(11, "刷牙");
- map.put(15, "上厕所");
- //第一种遍历方式keySet()
- Set<Integer> keySet = map.keySet();
- Iterator<Integer> i = keySet.iterator();
- while(i.hasNext()){
- Integer key = i.next();
- System.out.println("键是:" + key + "值是:" + map.get(key));
- }
- }
- }
运行结果:
3)TreeMap
与TreeSet同理,是红黑树结构存储,自然排序,key需要继承Comparable接口,自定义排序,则需传入Comparator对象。
示例:
- public class TreeMapDemo {
- public static void main(String[] args) {
- //String类已经继承Comparabe接口
- TreeMap<String, String> map = new TreeMap<String, String>();
- map.put("a", "aaaa");
- map.put("c", "cccc");
- map.put("d", "dddd");
- map.put("f", "ffff");
- map.put("q", "qqqq");
- Set<String> keySet = map.keySet();
- Iterator<String> i = keySet.iterator();
- while(i.hasNext()){
- String key = i.next();
- System.out.println("键是:" + key + "值是:" + map.get(key));
- }
- }
- }
运行结果:
5.collections工具类
该工具类提供了大量的方法对集合元素进行增删改查等操作。还提供了将集合对象设置为不可变、对集合对象实现同步控制等方法。
1)排序操作
示例:
- public class Demo10 {
- public static void main(String[] args) {
- List list = new ArrayList<Integer>();
- list.add(4);
- list.add(3);
- list.add(12);
- list.add(-9);
- //对list随机排序
- Collections.shuffle(list);
- print(list);
- //自然排序
- Collections.sort(list);
- print(list);
- }
- public static void print(List<Integer> arr){
- for(Integer str:arr){
- System.out.print(str + " ");
- }
- System.out.println();
- }
- }
运行结果:
2)查找替换操作
示例:
- public class Demo10 {
- public static void main(String[] args) {
- List list = new ArrayList<Integer>();
- list.add(4);
- list.add(3);
- list.add(12);
- list.add(-9);
- //自然排序
- Collections.sort(list);
- print(list);
- //查找、替换
- System.out.println("最大元素是:" + Collections.max(list));
- System.out.println("4的索引是:" + Collections.binarySearch(list, 4));
- System.out.println("替换所有的元素:" );
- Collections.fill(list, 1);
- print(list);
- }
- public static void print(List<Integer> arr){
- for(Integer str:arr){
- System.out.print(str + " ");
- }
- System.out.println();
- }
- }
运行结果:
3)同步操作
示例:
- public static void main(String[] args) {
- Collection collection = Collections.synchronizedCollection(new ArrayList());
- List list = Collections.synchronizedList(new ArrayList());
- Map map = Collections.synchronizedMap(new HashMap());
- Set set = Collections.synchronizedSet(new HashSet());
- }
4)设置不可变操作
示例:
- public static void main(String[] args) {
- List list = new ArrayList<Integer>();
- list.add(4);
- list.add(3);
- list.add(12);
- list.add(-9);
- List unmodifiableList = Collections.unmodifiableList(list);
- System.out.println(unmodifiableList.add(2));
- }
运行结果:
发生异常