Java基础12-工具类;变长参数;IO

作业解析

  1. 取出整数的16进制表示形式 \u00ff

     /**
      * int2hex
      * */
     public static String int2hex(int i) {
         String str = "0x";
         char[] c = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
         for(int j=28;j>=0;j=j-4) {
             str = str + c[(i>>j)&0xf];
         }
         return str;
     }
    
  2. 取出整数的8进制表示形式

     /**
      * int2oct
      * */
     public static String int2oct(int i) {
         String str = "";
         char[] c = {'0','1','2','3','4','5','6','7'};
         for(int j=30;j>=0;j=j-3) {
             str = str + c[(i>>j)&7];
         }
         return str;
     }
    
  3. 使用韩语字符集实现字符串编解码

     public static void main(String[] args) throws Exception {
             //使用韩语字符集实现字符串编码
             String str = "한국어";
             System.out.println(str);//한국어
             
             //utf-8编码解码
             byte[] Byte = str.getBytes("utf-8");
             System.out.println(new String(Byte,"utf-8"));//한국어
    
             //GB2312编码解码
             Byte = str.getBytes("GB2312");
             System.out.println(new String(Byte,"GB2312"));//???
    
             //EUC-KR编码解码
             Byte = str.getBytes("EUC-KR");
             System.out.println(new String(Byte,"EUC-KR"));//한국어
         }
    
  4. 字符串倒序排列

     public static void main(String[] args) throws Exception {
         //字符串倒序排列
         String str = "abcd1234";
         byte[] Bytes = str.getBytes("utf-8");
         byte[] Bytes2 = new byte[Bytes.length];
         for(int i=Bytes.length-1;i>=0;i--) {
             Bytes2[Bytes.length-1-i]=Bytes[i];
         }
         System.out.println(new String(Bytes2,"utf-8"));
     }
    
  5. 练习自动拆箱和装箱

     int i = 12;
     Integer ii = i;
     System.out.println(ii);//12
     int j = ii;
     System.out.println(j);//12
    
  6. 实现equals方法,比较四方面要素,Student

     public class Student {
         private String name;
         private int age;
         private int height;
         private int weight;
         public Student(String name, int age, int height, int weight) {
             this.name = name;
             this.age = age;
             this.height = height;
             this.weight = weight;
         }
         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 int getHeight() {
             return height;
         }
         public void setHeight(int height) {
             this.height = height;
         }
         public int getWeight() {
             return weight;
         }
         public void setWeight(int weight) {
             this.weight = weight;
         }
         @Override
         public boolean equals(Object obj) {
             if(obj==this) {
                 return true;
             }
             if(obj==null) {
                 return false;
             }
             //精准匹配
             if(obj.getClass()==Student.class) {
                 Student s = (Student)obj;
                 //判断姓名
                 boolean nameEqu = false;
                 if(s.getName()==null) {
                     if(this.getName()==null) {
                         nameEqu = true;
                     }
                     else {
                         nameEqu = false;
                     }
                 }
                 else {
                     nameEqu = s.getName().equals(this.getName());
                 }
    
                 boolean ageEqu = false;
                 if(s.getAge()==this.getAge()) {
                     ageEqu = true;
                 }
                 boolean heightEqu = false;
                 if(s.getHeight()==this.getHeight()) {
                     heightEqu = true;
                 }
                 boolean weightEqu = false;
                 if(s.getWeight()==this.getWeight()) {
                     weightEqu = true;
                 }
                 return nameEqu && ageEqu && heightEqu && weightEqu;
             }
             return false;
         }
     }
     Student s1 = new Student("s1", 10, 10, 10);
     Student s2 = new Student(null, 10, 10, 10);
     Student s3 = new Student(null, 10, 10, 10);
     Student s4 = new Student("s1", 10, 10, 10);
     
     System.out.println(s1.equals(new Student("s2", 10, 10, 10)));//false
     System.out.println(s1.equals(new Student("s1", 10, 10, 10)));//true
     
     System.out.println(s1==s1);//true
     System.out.println(s1.equals(s1));//true
     
     System.out.println(s1==s4);//false
     System.out.println(s1.equals(s4));//true
     
     System.out.println(s2==s3);//false
     System.out.println(s2.equals(s3));//true
     
     System.out.println(s1==s2);//false
     System.out.println(s1.equals(s2));//false		
     
     System.out.println(s1.equals(null));//false	
    
  7. 创建集合,存放10个person对象,5个Car对象,3个Bee对象,迭代集合,输出每个对象的name属性

     public class Person {
         private String name;
    
         public Person(String name) {
             super();
             this.name = name;
         }
    
         public String getName() {
             return name;
         }
    
         public void setName(String name) {
             this.name = name;
         }
     }
    
     public class Car {
         private String name;
         private int no;
    
         public Car(String name, int no) {
             super();
             this.name = name;
             this.no = no;
         }
         public String getName() {
             return name;
         }
         public void setName(String name) {
             this.name = name;
         }
         public int getNo() {
             return no;
         }
         public void setNo(int no) {
             this.no = no;
         }
     }
    
     public class Bee {
         private String name;
    
         public Bee(String name) {
             super();
             this.name = name;
         }
    
         public String getName() {
             return name;
         }
    
         public void setName(String name) {
             this.name = name;
         }
     }
    
     public static void main(String[] args) {
         List list = new ArrayList();
         
         //存放人
         for(int i=0;i<10;i++) {
             list.add(new Person("p"+i));
         }
         //存放汽车
         for(int i=0;i<5;i++) {
             list.add(new Car("c"+i,i));
         }
         //存放蜜蜂
         for(int i=0;i<3;i++) {
             list.add(new Bee("b"+i));
         }
    
         Iterator it = list.iterator();
         while(it.hasNext()) {
             Object obj = it.next();
             //精准匹配
             if(obj.getClass()==Person.class) {
                 Person p = (Person)obj;
                 System.out.println(p.getName());
             }
             if(obj.getClass()==Bee.class) {
                 Bee b = (Bee)obj;
                 System.out.println(b.getName());
             }
             if(obj.getClass()==Car.class) {
                 Car c = (Car)obj;
                 System.out.println(c.getName());
             }
         }
     }
    
  8. 使用Map集合实现嵌套: 操场上六个年级,每个年级有10班,每个班有60人(String)
    tom-x-y-n

     /**
      * 使用Map集合实现嵌套: 操场上六个年级,每个年级有10班,每个班有60人(String)tom-x-y-n
      * */
     public class MapDemo {
    
         public static void main(String[] args) {
             //定义年级
             Map<Integer, Map<Integer, Map<Integer,String>>> grades = new HashMap<Integer, Map<Integer,Map<Integer,String>>>();
             //定义班级
             Map<Integer, Map<Integer,String>> classes = null;
             for(int x=1;x<=6;x++) {	
                 classes = new HashMap<Integer, Map<Integer,String>>();
                 grades.put(x, classes);
                 //定义名单
                 Map<Integer,String> names = null;
                 for(int y=1;y<=10;y++) {
                     names = new HashMap<Integer,String>();
                     classes.put(y, names);
                     for(int n=1;n<=60;n++) {
                         names.put(n, "tom-"+x+"-"+y+"-"+n);
                         System.out.println("tom-"+x+"-"+y+"-"+n);
                     }
                 }
             }
    
             //迭代嵌套的Map集合
             System.out.println("======使用KeySet==========");
             outMapwithKey(grades);
    
             System.out.println("======使用EntrySet========");
             outMapwithEntry(grades);
    
             System.out.println("=======使用迭代器==========");
             outMapwithIterator(grades);
    
         }
    
         /**
          * 使用key迭代
          * */
         private static void outMapwithKey(Map<Integer, Map<Integer, Map<Integer, String>>> grades) {
             //取出年级key
             Set<Integer> gradeSet = grades.keySet();
             for(Integer gradeKey : gradeSet) {
                 Map<Integer, Map<Integer, String>> gradeValue = grades.get(gradeKey);
                 //取出班级key
                 Set<Integer> classSet = gradeValue.keySet();
                 for(Integer classKey: classSet) {
                     Map<Integer, String> classValue= gradeValue.get(classKey);
                     //取出名单key
                     Set<Integer> names= classValue.keySet();
                     for(Integer name: names) {
                         String s = classValue.get(name);
                         System.out.println(gradeKey+"-"+classKey+"-"+name+":"+s);
                     }
                 }
             }
         }
         /**
          * 使用条目迭代
          * */
         private static void outMapwithEntry(Map<Integer, Map<Integer, Map<Integer, String>>> grades) {
             //取出年级条目:年级id ------> 班级集合
             Set<Entry<Integer,Map<Integer, Map<Integer, String>>>> gradeEntries = grades.entrySet();
             for(Entry<Integer,Map<Integer, Map<Integer, String>>> gradeEntry: gradeEntries) {
                 //依次取出每个条目的键:年级id,每个条目的值:班级条目集合
                 Integer gradekey = gradeEntry.getKey();
                 Map<Integer, Map<Integer, String>> classes = gradeEntry.getValue();
    
                 //取出班级条目:班级id ------> 名单集合
                 Set<Entry<Integer, Map<Integer, String>>> classEntries = classes.entrySet();
                 for(Entry<Integer, Map<Integer, String>> classEntry : classEntries) {
                     //依次取出每个条目的键:班级id,每个条目的值:名单条目集合
                     Integer classKey = classEntry.getKey();
                     Map<Integer, String> classValue= classEntry.getValue();
                     System.out.println(gradekey+"年"+classKey+"班"+":");
                     //取出名单条目:学生id ----> 学生姓名
                     Set<Entry<Integer, String>>  namesEntries = classValue.entrySet();
                     for(Entry<Integer, String> namesEntry : namesEntries) {
                         Integer namesKey = namesEntry.getKey();
                         String namesValue =  namesEntry.getValue();
                         System.out.println(gradekey+"-"+classKey+"-"+namesKey+":"+namesValue);
                     }
                 }
             }
         }
    
         /**
          * 使用迭代器迭代
          * */
         private static void outMapwithIterator(Map<Integer, Map<Integer, Map<Integer, String>>> grades) {
             //取出年级条目:年级id ------> 班级集合
             Set<Entry<Integer,Map<Integer, Map<Integer, String>>>> gradeEntries = grades.entrySet();
             //一级迭代器,迭代年级条目
             Iterator<Entry<Integer,Map<Integer, Map<Integer, String>>>> it = gradeEntries.iterator();
             while(it.hasNext()) {
                 //利用一级迭代器依次取出年级id,班级集合
                 Entry<Integer,Map<Integer, Map<Integer, String>>> gradeEntry= it.next();
                 Integer gradeKey = gradeEntry.getKey();
                 Map<Integer, Map<Integer, String>> gradeValue = gradeEntry.getValue();
    
                 //二级迭代器,迭代班级条目
                 Set<Entry<Integer, Map<Integer, String>>> classEntries = gradeValue.entrySet();
                 Iterator<Entry<Integer, Map<Integer, String>>> it2 = classEntries.iterator();
                 while(it2.hasNext()) {
                     //利用二级迭代器依次取出班级id,名单集合
                     Entry<Integer, Map<Integer, String>> classEntry= it2.next();
                     Integer classKey = classEntry.getKey();
                     Map<Integer, String> classValue = classEntry.getValue();
    
                     //三级迭代器,迭代学生名单
                     Set<Entry<Integer, String>> nameEntries = classValue.entrySet();
                     Iterator<Entry<Integer, String>> it3 = nameEntries.iterator();
                     while(it3.hasNext()) {
                         //利用三级迭代器依次取出学生id,姓名
                         Entry<Integer, String> nameEntry = it3.next();
                         Integer nameKey = nameEntry.getKey();
                         String nameValue = nameEntry.getValue();
                         System.out.println(gradeKey+"-"+classKey+"-"+nameKey+":"+nameValue);
                     }
                 }
             }
         }
     }
    
  9. 定义罪犯Criminal类,height(身高)/weight(体重)/blood(血型)/home(籍贯)属性。
    重写hashcode和equals,使用四个属性的组合进行实现。
    创建HashSet集合,里面存放20个Criminal对象,其中O型血2人,A型血3人,B型血4人,AB型血1人,其余血型不详。
    注意:hashcode()方法实现时,要求身高、体重、和血型三个属性合成一个数字,实现两两比较的高效算法。

  10. 创建HashMap, Person为key, Dog 为value。
    存放100元素,遍历map集合,两种方式:EntrySet + KeySet

    public class Person {
        private String name;
    
        public Person(String name) {
            super();
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public int hashCode() {
            if(name!=null) {
                return name.hashCode();			
            }
            else {
                return 0;
            }
        }
        @Override
        public boolean equals(Object obj) {
            if(obj==null) {
                return false;
            }
            if(obj==this) {
                return true;
            }
            if(obj.getClass()==Person.class) {
                Person p = (Person)obj;
                if(p.getName()==null) {
                    if(this.getName()==null) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    return p.getName().equals(this.getName());
                }
            }
            return false;
        }
        @Override
        public String toString() {
            return name;
        }
    }
    
    public class Dog {
        private String name;
        private String color;
        private String categraory;
        public Dog(String name, String color, String categraory) {
            super();
            this.name = name;
            this.color = color;
            this.categraory = categraory;
        }
        @Override
        public String toString() {
            return name+"-"+color+"-"+categraory;
        }
    }
    
    /**
     * 创建HashMap, Person为key, Dog 为value。存放100元素,遍历map集合,两种方式:EntrySet + KeySet
     * */
    public static void main(String[] args) {
        Map<Person,Dog> map = new HashMap<Person, Dog>();
        map.put(new Person("p1"), new Dog("d1","black","Jing8"));
        map.put(new Person("p1"), new Dog("d1","black","Jing8"));
        map.put(new Person(null), new Dog("d1","black","Jing8"));
        map.put(new Person(null), new Dog("d1","black","Jing8"));
        map.put(null, new Dog("d1","black","Jing8"));
        map.put(null, new Dog("d1","black","Jing8"));
        System.out.println(map.size());//没有重写hashcode()和equals()方法之前,结果为5; 
        System.out.println(map.size());//重写 equals方法之后,结果仍为5;
        System.out.println(map.size());//重写hashcode和equals方法后,结果为3
    
        //存放100个条目
        map.clear();
        for(int i=0;i<100;i++) {
            map.put(new Person("p"+i), new Dog("d"+i,"black","Jing8"));
        }
    
        //使用EntrySet遍历
        Set<Entry<Person,Dog>> entries = map.entrySet();
        for(Entry<Person,Dog> entry : entries) {
            Person key = entry.getKey();
            Dog value = entry.getValue();
            System.out.println(key+":"+value);
        }
    
        //使用keySet遍历
        System.out.println("=====================");
        Set<Person> keys = map.keySet();
        for(Person key: keys) {
            Dog value = map.get(key);
            System.out.println(key+":"+value);
        }
    }
    

工具类,变长参数

  1. Collections

     public class Person implements Comparable<Person> {
         private String name="";
    
         public Person(String name) {
             super();
             this.name = name;
         }
    
         public String getName() {
             return name;
         }
    
         public void setName(String name) {
             this.name = name;
         }
         @Override
         public String toString() {
             return name;
         }
    
         @Override
         public int compareTo(Person o) {
             return this.name.compareTo(o.getName());
         }
     }
    
     public class CollectionToolDemo {
    
         public static void main(String[] args) {
             List<String> list = new ArrayList<String>();
             list.add("a");
             list.add("abc");
             list.add("123");
             list.add("中国");
             list.add("法国人");
             list.add("");
    
             outEle(list);//a,abc,123,中国,法国人,,
    
             //使用工具类排序
             Collections.sort(list);
             outEle(list);//,123,a,abc,中国,法国人,
    
             //取出最大值
             String max = Collections.max(list);
             System.out.println("max="+max);//max=法国人
    
             //取出最小值
             String min = Collections.min(list);
             System.out.println("min="+min);//min=
    
             //反序(非反向排序)
             Collections.reverse(list);
             outEle(list);//法国人,中国,abc,a,123,,
    
             //交换元素位置
             Collections.swap(list, 1, 3);
             outEle(list);//法国人,a,abc,中国,123,,
    
             List<Person> list2 = new ArrayList<Person>();
             list2.add(new Person("熊大"));
             list2.add(new Person("光头强"));
             list2.add(new Person("熊二"));
    
             outEle(list2);//熊大,光头强,熊二,
    
             Collections.sort(list2);//需要实现Comparable接口才可以排序
             outEle(list2);//光头强,熊二,熊大,
    
         }
         /**
          * 输出集合元素
          * */
         public static void outEle(List<? extends Object> list) {
             for(Object s: list) {
                 System.out.print(s+",");
             }
             System.out.println();
         }
     }
    
  2. Arrays

     public static void main(String[] args) {
         int[] a = new int[]{1,3,5,7};
         int[] a2 = copyArr(a);
         System.out.println(a2.length);//4
         int[] a3 = Arrays.copyOf(a, 2);
         System.out.println(a3);
    
         //二分法查找
         System.out.println(Arrays.binarySearch(a, 7));//3
         System.out.println(Arrays.binarySearch(a, 0,3,7));//-4
    
         //转数组为列表
         List<Integer> list = Arrays.asList(1,2,3,4);
         System.out.println(list.size());
     }
     public static int[] copyArr(int[] arr) {
         //健壮性
         if(arr==null || arr.length==0) {
             return arr;
         }
         int[] arr2 = new int[arr.length];
         for(int i=0;i<arr.length;i++) {
             arr2[i] = arr[i];
         }
         return arr2;
     }
    
  3. 变长参数
    变长参数必须是方法的最后一个参数
    public void addTel(String s1, String... str); //ok
    public void addTel(String... str,String s1); //error

     public static void main(String[] args) {
         outArr("1","2","3","4","5");
     }
     //变长参数只能有一个,且必须是最后一位形参
     public static void outArr(String...str) {
         for(String s:str) {
             System.out.println(s);
         }
     }
    

集合内容回顾

  1. list

    • ArrayList //不安全
    • LinkedList // 不安全
    • Vector // 线程安全
  2. Set

    • Hashset, hashmap
    • TreeSet: 有序,Comparable
      排序实现方式:
      1)实现Comparable接口, interface Comparable{int compare}
      2)Comparator,对比器
  3. Map

    • HashMap: key(键) - value(值) KV====Entry

    • HashTable: 线程安全

IO

  1. 分类

    • 按流向:
      输入流 Input
      输出流 Output
    • 按类型:
      字节型: InputStream, OutputStream
      字符型: Reader, Writer
  2. 编译时异常:需要在代码中对异常进行声明或捕获

  3. FileWriter

     public static void main(String[] args) {
         FileWriter fw = null;
         try {
             fw = new FileWriter("d:\\fileWriter.txt");;
             fw.write("Hello, FileWriter");
             System.out.println("over");
         } catch (IOException e) {
             e.printStackTrace();
         }
         finally {
             //释放资源
             try {
                 if(fw!=null) {					
                     fw.close();
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
    
    • new FileWriter(String path);

    • Writer(String str);
      写入字符数据到流中

    • flush()
      清理流,将流中的数据写入目标设备上

    • close()
      关闭流,隐含了flush操作。流在close之后,无法再写入数据,重复关闭不会导致问题

  4. FileReader
    不支持reset(),不支持mark(),支持skip

     public static void main(String[] args) throws Exception {
         FileReader fr = new FileReader("d:\\fileWriter.txt");
         int i = 0;
         while((i=fr.read())!=-1) {
             System.out.print((char)i);
         }
         fr.close();
    
    
         //do...while
         System.out.println("================");
         i=-1;
         fr = new FileReader("d:\\fileWriter.txt");
         do {
             i = fr.read();
             if(i!=-1) {
                 System.out.print((char)i);				
             }
         }while(i!=-1);
         fr.close();
    
         //使用char[]缓冲区读取文件
         System.out.println("============");
         fr = new FileReader("d:\\fileWriter.txt");
         //fr.reset();//不支持
         //fr.markSupported();//false
         char[] buf = new char[10];
         int len = 0;
         while((len=fr.read(buf))!=-1) {
             System.out.print(new String(buf,0,len));
         }
         fr.close();
     }
    

作业

  1. 描述HashMap内部实现原理

  2. List Set Map区别

  3. 描述HashSet和HashMap的区别

  4. 编程实现文本文件的复制。合理设计程序,得到缓冲区的大小的高效区间。
    提示缓冲区设置1k开始,不超过10M。

  5. 使用FileWriter,将1-1000000写入到文本中

  6. 变长参数 + 增强for循环

posted @ 2019-04-17 08:49  Shinesu  阅读(135)  评论(0编辑  收藏  举报