java集合类

集合类之间逻辑关系

在这里插入图片描述

Collection

package collectionTest;
//
import java.util.ArrayList;
import java.util.Iterator ;
import java.util.Collection;
//
//
//
import student.Student;
//
public class collectionTest01 {
  public static void main(String[] args) {
 //
  //collection是接口不能实例化
 Collection col1=new ArrayList();//多态特性
 //add添加元素
 col1.add("a");
 col1.add("b");
 col1.add("s");
 //System.out.println(col1);
 //
 //clear清空元素
 col1.clear();
 System.out.println(col1);
 //
 //add加对象
 Student stu1 = new Student();
 stu1.setName("zhansan");
 stu1.setAge(10);
 col1.add(stu1);
 Student stu2 = new Student();
 stu2.setName("lisi");
 stu2.setAge(20);
 col1.add(stu2);
 Student stu3 = new Student();
 stu3.setName("wanwu");
 stu3.setAge(30);
 col1.add(stu3);
 System.out.println(col1);
 //
 //获取元素个数
 System.out.println(col1.size());
 //
 //addAll添加整个集合
 Collection col2=new ArrayList();
 col2.add(stu1);
 col2.add(stu2);
 col1.addAll(col2);
 System.out.println(col1);
 //
 //判断集合是否包含某元素
 System.out.println(col1.contains(stu2));
 //
 //判断集合是否包含某集合
 System.out.println(col1.containsAll(col2));
 //
 //判断集合是否为空
 System.out.println(col1.isEmpty());
 //
 //迭代器 遍历元素
 Collection col3 = new ArrayList();
 col3.add("a");
 col3.add("b");
 col3.add("c");
 Iterator iter= col3.iterator();
 while(iter.hasNext()) {//是否含有下一个
  String result=(String) iter.next();
  //System.out.println(result);
 }
 //
 //删除指定元素
 col3.remove("b");
 //System.out.println(col3);
 //
// 删除指定集合元素
   Collection col4=new ArrayList();
   col4.add("a");
   col4.add("c");
   col3.removeAll(col4);
   System.out.println(col3);
   col3.remove("a");
   //
   //仅保留指定元素
   col4.retainAll(col3);
   System.out.println(col4);
   //将集合转数组
   Object[] col1Array = col4.toArray();
   System.out.println(col1Array[0]);
}
}
 

ArrayList & LinkedList

  • ArrayList长于随机访问元素,但在中间插入和移除元素时较慢
  • LinkedList,长于中间插入和移除,但对于随机访问较慢

ArrayList

package collectionTest.List;
//
import  java.util.List;
import java.util.ArrayList;
//
public class ListTest {
public static void main(String[] args) {
 //System.out.println("hello");
 ArrayList list1 = new ArrayList();
 list1.add("a");
 list1.add("b");
 list1.add("c");
 list1.add("d");
 System.out.println(list1);
 //
 //Arrays.asList()方法接受一个数组或用逗号分隔的元素列表(可变参数) 并将其转换为一个List对象
	Collection<Integer> col=new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
	System.out.println(col);
	Integer[] mol= {6,7,8,9,10};
	col.addAll(Arrays.asList(mol));
	System.out.println(col);
	//Collections.addAll()方法接受一个Collection对象,以及一个数组或用逗号分隔的元素列表
	Collections.addAll(col, 11,12,13,14,15);
	System.out.println(col);
	Collections.addAll(col,mol);
	System.out.println(col);
	List<Integer> list=Arrays.asList(16,17,18,19,20);
	list.set(1, 99);
	System.out.println(list);
	//运行错误 底层为一数组
	//list.add(21);
 
 //方法重载 添加到指定位置 插入到位置
 list1.add(1,"e");
 System.out.println(list1);
 //
 //添加指定集合到指定位置
    ArrayList list2=new ArrayList();
    list2.add(1);
    list2.add(2);
    System.out.println(list2);
    list1.addAll(2, list2);
//    System.out.println(list1);
    //
    //返回指定位置元素 类型为object
    Object object = list1.get(2);
    System.out.println(object);
    //
    //返回指定元素所在位置  未找到返回-1
    int index=list1.indexOf(2);
    System.out.println(index);
    //
    //从后往前找
    list1.add("e");
    System.out.println(list1);
    int index1=list1.lastIndexOf("e");
    System.out.println(index1);
    //删除第一次出现的指定元素 没有返回false
    list1.remove("e");
    System.out.println(list1);
    //
    //也可以删除指定位置元素
    list1.remove(1);
    System.out.println(list1);
    //
    //将指定位置元素修改
    list1.set(2, "hao");
    System.out.println(list1);
    //
    //截取
    List subList1 = list1.subList(2, 4);
    System.out.println(subList1);
    //都会返回true
    list1.containsAll(subList1);
    Collections.sort(subList1);
    list1.containsAll(subList1);
    Collections.shuffle(subList1);
    list1.containsAll(subList1);
}
}

LinkList&&HashSet

package collectionTest.LinkList;
//
import java.util.HashSet;
import java.util.LinkedList;
//
import javax.rmi.ssl.SslRMIClientSocketFactory;
//
public class TestLinkList {
  public static void main(String[] args) {
 LinkedList list1 = new LinkedList();
 list1.add("hello");
 list1.add("world");
 //独有方法
 list1.addLast("china");
 list1.addFirst("America");
 System.out.println(list1);
 //获得列表第一个元素
 list1.getFirst();
 list1.element();
 //删除并返回第一个元素 在列表为空时返回异常
 list1.remove();
 list1.removeFirst();
 //删除并返回最后一个元素
 ListremoveLast();
 //按位置删除
 list1.remove(1);
 System.out.println(list1);
 //
 list1.remove("world");
 System.out.println(list1);
 //
 HashSet set1 = new HashSet();
 set1.add("a");
 set1.add("b");
 set1.add("e");
 set1.remove("a");
 System.out.println(set1);
}
}

Stack

栈通常是后进后出的容器,LinkedList具有直接实现栈功能的方法

import java.util.LinkedList;
//参数化类型
public class Stack<T> {
  private LinkedList<T> storage = new LinkedList<T>();
  public void push(T v) { storage.addFirst(v); }
  public T peek() { return storage.getFirst(); }//提供栈顶元素
  public T pop() { return storage.removeFirst(); }
  public boolean empty() { return storage.isEmpty(); }
  public String toString() { return storage.toString(); }
} ///:~

队列Queue

import java.util.*;
//LinkedList提供了方法支持队列,并且它实现了Queue接口
public class Queue1 {
  public static void printQ(Queue queue) {//向上转型
    while(queue.peek() != null)//返回队头
      System.out.print(queue.remove() + " ");
    System.out.println();
  }
  public static void main(String[] args) {
    Queue<Integer> queue = new LinkedList<Integer>();
    Random rand = new Random(47);
    for(int i = 0; i < 10; i++)//在允许的情况下,将一个元素插入到队尾
      queue.offer(rand.nextInt(i + 10));
    printQ(queue);
    Queue<Character> qc = new LinkedList<Character>();
    for(char c : "Brontosaurus".toCharArray())
      qc.offer(c);
    printQ(qc);
  }
} /* Output:
8 1 1 1 5 14 3 1 0 1
B r o n t o s a u r u s
*///:~

PriorityQueue

import java.util.*;
//
public class PriorityQueueDemo {
  public static void main(String[] args) {
    PriorityQueue<Integer> priorityQueue =
      new PriorityQueue<Integer>();
    Random rand = new Random(47);
    for(int i = 0; i < 10; i++)
      priorityQueue.offer(rand.nextInt(i + 10));
    Queue1.printQ(priorityQueue);//优先输出小的
//
    List<Integer> ints = Arrays.asList(25, 22, 20,
      18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25);
    priorityQueue = new PriorityQueue<Integer>(ints);
    Queue1.printQ(priorityQueue);
    priorityQueue = new PriorityQueue<Integer>(
        ints.size(), Collections.reverseOrder());//转变优先级
    priorityQueue.addAll(ints);
    Queue1.printQ(priorityQueue);
//
    String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION";
    List<String> strings = Arrays.asList(fact.split(""));
    PriorityQueue<String> stringPQ =
      new PriorityQueue<String>(strings);//空格也有优先级
    Queue1.printQ(stringPQ);
    stringPQ = new PriorityQueue<String>(
      strings.size(), Collections.reverseOrder());
    stringPQ.addAll(strings);
    Queue1.printQ(stringPQ);
//
    Set<Character> charSet = new HashSet<Character>();
    for(char c : fact.toCharArray())
      charSet.add(c); // Autoboxing
    PriorityQueue<Character> characterPQ =
      new PriorityQueue<Character>(charSet);//Set的优先级
    Queue1.printQ(characterPQ);
  }
} /* Output:
0 1 1 1 1 1 3 5 8 14
1 1 2 3 3 9 9 14 14 18 18 20 21 22 23 25 25
25 25 23 22 21 20 18 18 14 14 9 9 3 3 2 1 1
       A A B C C C D D E E E F H H I I L N N O O O O S S S T T U U U W
W U U U T T S S S O O O O N N L I I H H F E E E D D C C C B A A
  A B C D E F H I L N O S T U W
*///:~

Set

import java.util.*;
//
public class SetOfInteger {
/*  public static void main(String[] args) {
    Random rand = new Random(48);
    //查找时set中最重要的操作
    Set<Integer> intset = new HashSet<Integer>();
    for(int i = 0; i < 10000; i++)
      intset.add(rand.nextInt(30));//随机产生0~29
    System.out.println(intset);
  }*/
	//
		  public static void main(String[] args) {
		    Random rand = new Random(47);
		    SortedSet<Integer> intset = new TreeSet<Integer>();
		    for(int i = 0; i < 10000; i++)
		      intset.add(rand.nextInt(30));
		    System.out.println(intset);
		  }
		} 
/* Output:
[15, 8, 23, 16, 7, 22, 9, 21, 6, 1, 29, 14, 24, 4, 19, 26, 11, 18, 3, 12, 27, 17, 2, 13, 28, 20, 25, 10, 5, 0]
*///:~
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
*///:~

Map
map中的key是唯一的;value是不唯一的

package map;//双值key - value
import java.util.*;
public class HashMapTest {//无序
  public static void main(String[] args) {
 HashMap map1 = new HashMap();
 map1.put("s01","zhangsan");
 map1.put("s02", "lisi");
 map1.put("s03","wangwu");
 System.out.println(map1);
 //
 Object v = map1.get("s01");
 System.out.println(v);
 //
 System.out.println(map1.containsKey("s01"));
 System.out.println(map1.containsValue("wangwu"));
 //转为单值集合,key only
 Set set = map1.keySet();
 System.out.println(set);
 Collection values = map1.values();
 System.out.println(values);
 //Remove 根据key删除  返回一个对象
 map1.remove("s04");
 System.out.println(map1);
}
}
import java.util.*;
//测试随机数产生次数
public class Map1 {
public static void main(String[] args) {
  Random rand = new Random(47);
  Map<Integer,Integer> m =
    new HashMap<Integer,Integer>();
  for(int i = 0; i < 10000; i++) {
    // Produce a number between 0 and 20:
    int r = rand.nextInt(20);
    Integer freq = m.get(r);
    m.put(r, freq == null ? 1 : freq + 1);
  }
  System.out.println(m);
}
} /* Output:
{15=497, 4=481, 19=464, 8=468, 11=531, 16=533, 18=478, 3=508, 7=471, 12=521, 17=509, 2=489, 13=506, 9=549, 6=519, 1=502, 14=477, 10=513, 5=503, 0=481}
*///:~

区别与联系

唯一:不能重复
有序:不是排序;是输入顺序 是否与 输出顺序一致的。

Collection:存储的数据是不唯一、无序的对象
List:存储的数据是 不唯一、有序的对象
Set:存储的数据是 唯一、无序的对象

Collection中的类(List、Set),删除的返回值是 boolean;
Map中的类,是根据Key删除,返回值是value.

Collections集合工具类

package collections;
import java.util.*;
//集合工具类
public class CollectionsTest {
public static void main(String[] args) {
 List<String> list=new ArrayList<>();
 list.add("x");
 list.add("i");
 list.add("o");
 list.add("n");
 list.add("g");
 //sort
 System.out.println(list);
 Collections.sort(list);
 System.out.println(list);
 //max min
// System.out.println(Collections.max(list));
// System.out.println(Collections.min(list));
 //二分查找,集合先排序 返回位置
// System.out.println(Collections.binarySearch(list, "g"));
 //
 //乱序
 Collections.shuffle(list);
 System.out.println(list);
 //reverse
 Collections.reverse(list);
 System.out.println(list);
 //swap
 Collections.swap(list, 0, 1);
 System.out.println(list);
 //replaceAll 元素内容
 Collections.replaceAll(list, "g", "G");
 System.out.println(list);
 //
 Collections.fill(list, "x");
 System.out.println(list);
}
}

迭代器Iterator

  • Iterator()要求返回一个Iteritor,且准备返回序列第一个元素
  • 使用next()获得序列下一个元素
  • 使用hasNext()检查序列是否还有元素
  • 使用remove()将迭代器新进的元素删除
    遍历容器元素
public class SimpleIteration {
  public static void main(String[] args) {
    List<Pet> pets = Pets.arrayList(12);
    Iterator<Pet> it = pets.iterator();
    while(it.hasNext()) {
      Pet p = it.next();
      System.out.print(p.id() + ":" + p + " ");
    }
    System.out.println();
    // A simpler approach, when possible:
    for(Pet p : pets)
      System.out.print(p.id() + ":" + p + " ");
    System.out.println();	
    // An Iterator can also remove elements:
    it = pets.iterator();
    for(int i = 0; i < 6; i++) {
      it.next();
      it.remove();
    }
    System.out.println(pets);
  }
} /* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster
[Pug, Manx, Cymric, Rat, EgyptianMau, Hamster]
*///:~

ListIterator
可以双向移动,可以产生当前位置前一个与后一个元素索引,也可以用set替换元素,调用ListIterator(n)指向索引为n元素的迭代器

public class ListIteration {
  public static void main(String[] args) {
    List<Pet> pets = Pets.arrayList(8);
    ListIterator<Pet> it = pets.listIterator();
    while(it.hasNext())
      System.out.print(it.next() + ", " + it.nextIndex() +
        ", " + it.previousIndex() + "; ");
    System.out.println();
    // Backwards:
    while(it.hasPrevious())
      System.out.print(it.previous().id() + " ");
    System.out.println();
    System.out.println(pets);	
    it = pets.listIterator(3);
    while(it.hasNext()) {
      it.next();
      it.set(Pets.randomPet());
    }
    System.out.println(pets);
  }
} /* Output:
Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
7 6 5 4 3 2 1 0
[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau]
*///:~

比较器

package collectionCompare;
//
public class Person {
private int id;
private String name;
private int age;
private String city;
//
public int getId() {
 return id;
}
public void setId(int id) {
 this.id = id;
}
public Person() {}
public Person(int id, String name, int age, String city) {
 super();
 this.id = id;
 this.name = name;
 this.age = age;
 this.city = city;
}
public Person(String name, int age, String city) {
 super();
 this.name = name;
 this.age = age;
 this.city = city;
}
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 String getCity() {
 return city;
}
public void setCity(String city) {
 this.city = city;
}
//打印对象直接tostring
@Override
public String toString() {
 return "Person [id=" + id + ", name=" + name + ", age=" + age + ", city=" + city + "]";
}
//内部比较器
//返回1降序,返回-1升序 ,返回零相等
/*@Override
public int compareTo(Object o) {
 // TODO Auto-generated method stub
 Person p=(Person)o;
 //降序
 int result= this.id<p.id?1:(this.id==p.id?0:-1);
 //id same
 if(result==0) {//默认升序
  result=this.name.compareTo(p.name);
 }
 return result;
}*/
}
package collectionCompare;
//
import java.util.Comparator;
//
public class Comparet implements Comparator{
 @Override
 public int compare(Object o1, Object o2) {
  // TODO Auto-generated method stub
  Person p1=(Person) o1;
  Person p2=(Person) o2;
  return p2.getId()-p1.getId();
 }
}

package collectionCompare;
import java.util.*;
public class Compare {
//外部部比较器
 public static void main(String[] args) {
  List<Person> persons=new ArrayList<Person>() ;
  Person p1=new Person(1,"zs",10,"nc");
  Person p2=new Person(4,"ls",13,"cs");
  Person p3=new Person(2,"wu",12,"nn");
  persons.add(p1);
  persons.add(p2);
  persons.add(p3);
  //Collections.sort(persons);如果person内写了就调用所写
  Collections.sort(persons,new Comparet());
  System.out.println(persons);
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值