Java基础10-集合

时间:2023-03-08 22:48:26
Java基础10-集合

作业回顾

  1. 蜜蜂和熊的生产消费关系,熊在蜂蜜满10斤吃掉。蜜蜂一次生产一斤蜂蜜,且蜜蜂生成一斤蜂蜜花费的时间是10s。

    十只蜜蜂和两只熊。

    • 蜜蜂

      bag: 20

      每次产1,耗时10ms

      满5的时候给蜜罐添加

    • 蜜罐

      max : 30



    • eat

        //蜜蜂线程
      public class Bee extends Thread{
      public static final int BAG=20;
      private int currentCount = 0;
      private String name;
      private Pool pool; public Bee(String name,Pool pool){
      this.name = name;
      this.pool = pool;
      }
      public void run(){
      while(true){
      synchronized(pool){
      //如果蜜罐当前量已满
      if(pool.currentNo>=Pool.MAX){
      //如果蜜蜂自身蜜囊已满,通知熊吃蜂蜜,并进入等待队列
      if(currentCount>=Bee.BAG){
      try{
      pool.notifyAll();
      pool.wait();
      }catch(Exception e){
      }
      }
      //如果蜜蜂自身蜜囊未满,通知熊吃蜂蜜,自身蜜囊加1
      else{
      pool.notifyAll();
      currentCount++;
      }
      }
      //如果蜜罐未满
      else{
      //蜜罐剩余的空间
      int count = Pool.MAX-pool.currentNo;
      //如果蜜蜂自身的量超过蜜罐剩余空间,则将蜜罐加满,自身的量相应减少
      if(currentCount>=count){
      pool.currentNo = Pool.MAX;
      currentCount = currentCount -count;
      pool.notifyAll();
      }
      //如果蜜罐自身的量不够蜜罐剩余空间,则全部加入到蜜罐中,自身的量清零
      else{
      pool.currentNo += currentCount;
      currentCount = 0;
      }
      }
      }
      }
      }
      } //熊线程
      public class Bear extends Thread{
      private String name;
      private Pool pool; public Bear(String name, Pool pool){
      this.name = name;
      this.pool = pool;
      }
      public void run(){
      while(true){
      synchronized(pool){
      if(pool.currentNo==Pool.MAX){
      System.out.println(name+"吃了蜂蜜:"+ pool.currentNo);
      pool.currentNo = 0;
      pool.notifyAll();
      }
      else{
      try{
      pool.wait();
      }
      catch(Exception e){
      }
      }
      }
      }
      }
      } //蜜罐类
      public class Pool{
      public static final int MAX=30;
      public int currentNo = 0;
      } //测试类
      public class App{
      public static void main(String[] args){
      Pool pool = new pool();
      Bee bee1 = new Bee("bee-1",pool);
      Bee bee2 = new Bee("bee-2",pool);
      Bee bee3 = new Bee("bee-3",pool);
      Bee bee4 = new Bee("bee-4",pool);
      Bee bee5 = new Bee("bee-5",pool);
      Bee bee6 = new Bee("bee-6",pool);
      Bee bee7 = new Bee("bee-7",pool);
      Bee bee8 = new Bee("bee-8",pool); Bear bear1 = new Bear("bear-1",pool); bee1.start();
      bee2.start();
      bee3.start();
      bee4.start();
      bee5.start();
      bee6.start();
      bee7.start();
      bee8.start(); bear1.start();
      }
      }
  2. 取出两个字符串中最大的公共子串。

     public class subStringDemo {
    public static void main(String[] args) { String str1 = "how中are国you123";
    String str2 = "your国are国howu123"; //System.out.println(str1.compareTo(str2));
    //String str3 = str1-str2; char c='a'; //System.out.println(str1.lastIndexOf(c));
    //System.out.println(str1.substring(0,str1.length())); System.out.println(str1.charAt(0));
    System.out.println(getMaxSameStr(str1,str2));//are国
    } /**
    * Find the max same subString of two strings 
    * */  
    public static String getMaxSameStr(String str1,String str2) {
    String maxSameStr="";
    String temp="";
    int len = str1.length();
    //从大到小在str1中取子串,和str2匹配
    // 缺陷,当有两个同样长度的公共子串时,只能找到前面一个
    for(int i=0;i<len;i++) {
    for (int j=0;j<=i;j++) {
    temp = str1.substring(j,j+len-i);
    if(str2.indexOf(temp)!=-1) {
    maxSameStr=temp;
    return maxSameStr;
    }
    }
    }
    return maxSameStr;
    }
    }
  3. StringBuffer是线程安全的,StringBuilder不是线程安全。单线程访问情况下,性能是否一致?

     public class StringBuilderBuffer {
    public static void main(String[] args) {
    //测试单线程访问情况下,StringBuilder与 StringBuffer的性能
    StringBuilder str1 = new StringBuilder();
    StringBuffer str2 = new StringBuffer(); long l1 = System.currentTimeMillis();
    for(int i=0;i<1000000;i++) {
    str1.append(i);
    }
    System.out.println(System.currentTimeMillis()-l1);//272 long l2 = System.currentTimeMillis();
    for(int j=0;j<1000000;j++) {
    str2.append(j);
    }
    System.out.println(System.currentTimeMillis()-l2);//434, StringBuffer是线程安全的,其方法中有同步这一步骤,因此访问较慢
    }
    }
  4. 完成8种基本数据类包装类的练习,完成自动拆装箱操作。

     import java.io.UnsupportedEncodingException;
    
     public class StringDemo {
    public static void main(String[] args) throws Exception {
    String str = "한국어";
    byte[] b = str.getBytes("euc_kr");
    /*
    int count = 0;
    for(int i=0;i<=0xffff;i++) {
    count++;
    System.out.print((char)i);
    if(count>=20) {
    count = 0;
    System.out.println();
    }
    }
    */
    System.out.println(new String(b,"euc_kr"));//한국어 //字符串倒序输出,不支持中文
    String str2 = "abcde123";
    byte[] b2 = str2.getBytes("utf-8");
    byte[] b3 = new byte[b2.length];
    for(int i = 0;i<b2.length;i++) {
    b3[i] = b2[b2.length-i-1];
    }
    System.out.println(new String(b3,"utf-8"));//321edcba
    //自动装箱
    Integer a = 12;
    System.out.println(a);//12
    //自动拆箱
    int i = a;
    System.out.println(i);//12
    }
    }
  5. substring(String str, int beginIndex, int length);

    返回一定长度的子串

     /**
    * return subString of String based on the given beginIndex and length
    * */
    public static String subString(String str, int beginIndex, int length){
    String subStr = null;
    if(str==null || str.length()==0) {
    System.out.println("字符串非法");
    return null;
    }
    if(beginIndex<0 || beginIndex>=str.length()) {
    System.out.println("开始索引非法");
    return null;
    } if(length<=0 || beginIndex+length>str.length()) {
    System.out.println("长度非法");
    return null;
    }
    return str.substring(beginIndex,beginIndex+length);
    }
  6. 找到自己名字对应的Unicode码

     for(int i=0;i<=0xffff;i++) {
    if((char)i=='翟') {
    System.out.println(i);
    int2hex(i);
    System.out.println((char)i);
    }
    if((char)i=='大') {
    System.out.println(i);
    int2hex(i);
    System.out.println((char)i);
    }
    if((char)i=='壮') {
    System.out.println(i);
    int2hex(i);
    System.out.println((char)i);
    }
    } public static void int2hex(int l) {
    char hex[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    System.out.print("0x");
    for(int i=28;i>=0;i=i-4) {
    System.out.print(hex[(l>>i)&0x0f]);
    }
    System.out.println();
    }

StringBuffer

  1. 字符串缓冲区

  2. mutable, 可变的

  3. java.lang.AbstractStringBuilder

    |--------java.lang.StringBuffer

  4. 线程安全的

StringBuilder

  1. 字符串构建器

  2. mutable, 可变的

  3. java.lang.AbstractStringBuilder

    |--------java.lang.StringBuilder

  4. 线程不安全

集合类

  1. List : 列表,接口 ArrayList()

     interface java.lang.Iterable
    /|\
    |------interface java.util.Collection
    /|\
    |-----interface java.util.List
    |---------------class java.util.ArrayList
    • ArrayList读取快,写入慢

      list.add(...);

      list.get(int index);

      list.remove(int index);

      list.clear();

    • LinkedList

      存储速度快,查询速度慢

      链表,手拉手实现的对象引用

  2. []数组

    length //长度属性

  3. String

    length() //方法.

    • ==判断的是对象的内存地址,不是对象的内容
    • equals方法判断是对象的内容是否相同
  4. interface Collection

    • size() //方法

    • isEmpty() // ==null ?

    • 判断集合有效性

      col != null && col.isEmpty()

    • contains(Object obj) //判断是否包含指定的对象

    • List //有序,可重复

    • Set //无序,不重复

    • Map //key-value

  5. instanceof(非精准判断)

    运算符,判断变量是否是指定类型的对象。

    boolean b = obj instanceof String ;

    String 是final类,不可以被继承

    精准判断须用:

    this.getClass()==obj.getClass();

练习

  1. 创建集合

    • 存放String[tom,tomas,tomsLee]

    • 存放Integer[100,200,300]

    • 存放Student{name,sex,age,标准javabean}[tom,tomas,tomsLee]

       List list = new ArrayList();
      //存放String
      list.add("tom");
      list.add("tomas");
      list.add("tomslee"); //存放Integer
      list.add(100);
      list.add(new Integer(200));
      list.add(300); //存放Student
      list.add(new Student("s-1",10,'f'));
      Student s = new Student("s-2",11,'m');
      list.add(s);
      list.add(new Student("s-3",12,'m')); Object obj = null;
      //利用索引遍历列表
      for(int i=0;i<list.size();i++) {
      obj = list.get(i);
      if(obj instanceof String) {
      System.out.println((String)obj);
      }
      else if(obj instanceof Integer) {
      System.out.println(100+(Integer)obj);
      }
      else {
      Student s2 = (Student)obj;
      System.out.println("name:"+s2.getName()+" age:"+s2.getAge()+" sex:"+s2.getSex());
      }
      }
      System.out.println("------------------");
      //利用迭代器遍历列表
      Iterator it = list.iterator();
      while(it.hasNext()) {
      System.out.println(it.next());
      }
  2. Student :

    判断学生类对象内容是否相同,重写equals方法。需要三个条件同时满足name + age + sex都相同才相同。

        public boolean equals(Object obj) {
    if(obj==null) {
    return false;
    }
    if(obj==this) {
    return true;
    } if(obj.getClass() == Student.class ) {
    Student s = (Student)obj;
    boolean nameEqu = false;
    boolean ageEqu = false;
    boolean sexEqu = false; if(s.getName()==null) {
    if(this.getName()==null) {                                  
    nameEqu = true;
    }
    else {
    nameEqu = false;
    }
    }
    else {
    nameEqu =  s.getName().equals(this.name);
    }
    /*if(this.age==s.getAge()) {
    ageEqu = true;
    }*/
    ageEqu = (this.age==s.getAge());
    /*if(this.sex == s.getSex()) {
    sexEqu = true;
    }*/
    sexEqu = (this.sex == s.getSex());
    return nameEqu && ageEqu && sexEqu;
    }
    return false;
    }
  3. 练习Vector向量类。

     //与AarryList的不同点在于,Vector是线程安全的
    Vector vector = new Vector();
    Student s1 = new Student("s1",10);
    //向集合中添加元素
    vector.add(s1);
    vector.add(new Student("s2",20)); //重复添加元素
    //添加的是重复的地址,匿名对象添加的是新地址(就算重写了equals方法,也是新地址)
    vector.add(s1);
    vector.add(new Student("s1",10));
    vector.add(new Student("s2",20)); System.out.println("重复添加元素,重写equals方法");
    Iterator it = vector.iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    } Student2 s2 = new Student2("s3",10);
    vector.add(s2);
    vector.add(s2);
    vector.add(new Student2("s3",10)); System.out.println("重复添加元素,没有重写equals方法");
    it = vector.iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    } //在指定位置插入元素,后续元素往后串
    vector.add(0, new Student("s3",30));
    //索引越界异常
    //vector.add(10,new Student("s4",30));
    System.out.println("在指定位置插入元素");
    it = vector.iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    } //删除元素,后续元素往前串
    System.out.println("按索引删除元素");
    vector.remove(0);
    it = vector.iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    }

作业:

  1. remove(int index); //删除指定位置的元素

  2. remove(Object o); //删除指定对象,考虑删除对象的规则是什么?

  3. removeAll(Collection col);//删除指定集合中的所有元素。

  4. contains(Object o); //是否包含

  5. contains(Collection col); //是否包含集合。