Map&泛型&Collection工具类&File总结

发布时间 2023-12-28 20:48:43作者: ZWJAS

总结

HashMap遍历方式

// 遍历map集合,Entry:键值对
// 遍历map的第一种方式:同时获取键和值,entrySet()
  Set set = hm.entrySet();// 获取所有的键值对
  System.out.println(set);
  Iterator it = set.iterator();
  while (it.hasNext()) {
      Object next = it.next();
      Map.Entry entry = (Map.Entry) next;
      Object key = entry.getKey(); // 获取键
      Object value = entry.getValue(); // 获取值
      System.out.println(key + ":" + value);
  }

// 遍历map的第二种方式:只获取键keySet()
Set set = hm.keySet();
for (Object key : set) {
    System.out.println(key + ":" + hm.get(key));
}

// 遍历map第三种方法:只获取值,values()
Collection values = hm.values();
Iterator it = values.iterator();
while (it.hasNext()) {
    Object next = it.next();
    System.out.println(next);
}

HashTable

1)、底层和HashMap相似
2)、不允许null为键null为值(空值空键)
3)、线程安全的

  • Properties

Properties:是HashTable的子类
底层也是一个map集合(保存键值对 Entry)
用来读取属性文件(什么是属性文件:保存键值对的文件)
以.properties结尾的文件就是属性文件

注意:为什么要将Entry放到属性文件中?解决硬编码问题

public class PropertiesDemo1 {
    public static void main(String[] args) throws IOException {
        Properties pp = new Properties();
        // load():将属性文件中键值对(Entry)加载到Properties对象里面
        pp.load(new FileInputStream("e:/name.properties"));
        // 取出pp中键值对
//        System.out.println(pp);
//        Set<Map.Entry<Object, Object>> entries = pp.entrySet();
//        Iterator<Map.Entry<Object, Object>> it = entries.iterator();
//        while (it.hasNext()) {
//            Map.Entry<Object, Object> next = it.next();
//            System.out.println(next.getKey() + ":" + next.getValue());
//        }
        // 从pp中把110为键对应值取出来
        String s = pp.getProperty("110");
        System.out.println(s);

    }
}

LinkedHashMap

LinkedHashMap:链表 + 哈希表

特点:保证键是有序的

public class MapDemo4 {
    public static void main(String[] args) {
        LinkedHashMap lhm = new LinkedHashMap();
        lhm.put("abc","张山");
        lhm.put(1,"张山山");
        lhm.put('A',"张三山");
        lhm.put(true,"张小山");
        lhm.put(3.14,"张一山");
        System.out.println(lhm);
    }
}

TreeMap

底层是一个树型结构,对元素进行排序(针对键来排序)
也是无序的map集合
注意:键必须是同一种类型

public class MapDemo5 {
    public static void main(String[] args) {
        TreeMap map = new TreeMap(); // 树型结构的map集合
        map.put(1,"abc"); // 键只能是同一种类型
        map.put(23,"bbc");
        map.put(2,"cbc");
        map.put(203,"dbc");
        System.out.println(map);
    }
}
  • 整理Map集合的体系结构
    -Map:映射根接口
    -HashMap:底层哈希表
    -LinkedHashMap:;链表 + 哈希表
    -HashTable:线程安全,且不允许空值空键
    -Properties:解析属性文件
    -TreeMap:底层是树型结构,对键进行排序
/**
*	String str = "ab3ca34bc5acb6cd6fs6da6bf6d",统计这个字符串中每个字母出现的次数,
*	并将结果保存到集合
*/
public static void main(String[] args) {
        // String str = "ab3ca34bc5acb6cd6fs6da6bf6d",统计这个字符串中每个字母出现的次数,并将结果保存到集合中
        String str = "ab3ca34bc5acb6cd6fs6da6bf6d";
        // 1、将字符串转为字符数组
        char[] chs = str.toCharArray();
        // 2、创建map集合
        HashMap<Character,Integer> hm = new HashMap<>(); // 使用泛型
        // 3、变量chs数组
        for (char c : chs) {
            if(Character.isLetter(c)) { // 判断字符是否为字母
                // 判断这个键在集合中是否存在
                if(hm.containsKey(c)) {
                    hm.put(c,hm.get(c) + 1);
                }else {
                    hm.put(c,1);
                }
            }
        
        }
     // 4、遍历集合
        Set<Map.Entry<Character, Integer>> entries = hm.entrySet();
        Iterator<Map.Entry<Character, Integer>> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<Character, Integer> entry = it.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
==============================================================================
/**
*	 产生10个1-100之间的随机数,要求不重复,并按降序排序
*/    
public class ReviewDemo {
    public static void main(String[] args) {
        // 产生10个1-100之间的随机数,要求不重复,并按降序排序
        TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        while (ts.size() < 10) {
            ts.add((int)(Math.random() * 100 + 1));
        }
        System.out.println(ts);
    }
}

泛型(generic)

泛型:特指某一种类型,防止数据的向上转型,使用过程中不用再向下转型类,简化操作
泛型的语法:<引用类型>,注意泛型不支持基本类型
泛型使用的范围

  1. 集合中
  2. 类和接口中
  3. 方法中

使用的语法:集合<数据类型:引用类型>:告诉JVM这个集合中只放这种类型的数据

泛型的嵌套:泛型里面可以包含泛型,<Map.Entry<String, String>>,外层泛型是Entry,内层泛型(嵌套泛型)是:String,String

泛型的上限和下限

:?表示任意类型,表示?的类型的上限是指定的类型 : :泛型的下限 ```java public static void main(String[] args) { // ArrayList list = new ArrayList(); // 没有使用泛型,这个集合所有类型都会向上转型为Object // ArrayList list = new ArrayList(); // 使用泛型 // ArrayList list = new ArrayList<>(); // 使用泛型 // list.add("abc"); // 使用泛型以后集合有检查机制 // list.add(10); // list.add(20); // list.add(30); // list.add(40); // Iterator it = list.iterator(); // while (it.hasNext()) { // Integer next = it.next(); // System.out.println(next); // } // HashMap hm = new HashMap<>(); // hm.put("abc","123"); // hm.put("bbc","132"); // hm.put("cbc","231"); // hm.put("dbc","321"); // Set> entries = hm.entrySet(); // Iterator> it = entries.iterator(); // while (it.hasNext()) { // Map.Entry next = it.next(); // System.out.println(next.getKey() + ":" + next.getValue()); // } ArrayList list = new ArrayList<>(); // 泛型上限 ArrayList list2 = new ArrayList<>(); // 泛型下限 } ``` - 泛型类 泛型类:在设计的类上使用泛型,这个类就是泛型类 ```java public class GenericDemo2 { public static void main(String[] args) { Pointer p = new Pointer<>(); Pointer p2 = new Pointer<>(); Pointer p3 = new Pointer<>(); } } // 设计一个表示坐标的类 Pointer //class Pointer { // private int x; // 横坐标 // private int y; // 纵坐标 //} // 这个类的坐标只能用int //class Pointer2 { // private double x; // private double y; //} // 以上的类属性的数据类型不能确定,所有相同了需要书写很多个,使用泛型类来处理 // 在Java中表示数据类型的符号(只能用于泛型) //规范的写法应该是使用一些字母(常见的字母): // E Element 元素:形参使用,任意的数据类型 // T Type 类型,类,接口,方法上使用 // K Key 键, // V Value 值 // 也可以支持多个泛型参数例如Map class Pointer { // 泛型类,T表示任意的数据类型 private T x; // 横坐标 private T y; // 纵坐标 // T的使用范围:在整个类的非static修饰的方法中使用 } ``` - 泛型方法 泛型方法:在一个方法上使用了泛型 ```java public class GenericDemo3{ // 设计一个方法用来合并两个数组 // public static int[] merge(int[] arr1,int[] arr2) { // // } // public static double[] merge(double[] arr1,double[] arr2) { // // } // 以上方法,参数的数据类型不确定,使用泛型方法来处理 // 泛型方法中泛型放在方法的返回值类型之前 public static T[] merge(T[] arr1, T[] arr2) { int len = arr1.length; arr1 = Arrays.copyOf(arr1,arr1.length + arr2.length); System.arraycopy(arr2,0,arr1,len,arr2.length); return arr1; } public static void main(String[] args) { // Integer[] arr1 = {1,2}; // Integer[] arr2 = {3,4}; // Integer[] merge = GenericDemo3.merge(arr1, arr2); // System.out.println(Arrays.toString(merge)); Double[] arr1 = {1.2,3.4,6.7}; Double[] arr2 = {1.2,3.4,6.7}; Double[] merge = GenericDemo3.merge(arr1, arr2); System.out.println(Arrays.toString(merge)); } } ``` ## Collections工具类 Collections是操作Collection集合的工具类,**全部是类方法** ```java public class CollectionsDemo1 { public static void main(String[] args) { ArrayList list = new ArrayList<>(); // 1、addAll(Collection c, T... elements) :向集合加入指定的数据 Collections.addAll(list,10,20,30,40,50,60); // 向list集合加入数据 System.out.println(list); // 2、binarySearch(List> list, T key):使用二分查找查询集合中元素的位置 int i = Collections.binarySearch(list, 300); System.out.println(i); // 3、fill(List list, T obj) :填充集合 // 4、max(Collection coll) :找出集合中最大的值 Integer max = Collections.max(list); System.out.println(max); // 5、min(Collection coll) :找出集合中最小的值 // 6、reverse(List list) :翻转集合元素
    Collections.reverse(list);
    System.out.println(list);

    // 7、shuffle(List<?> list):洗牌方法,打乱list集合中元素的顺序
    Collections.shuffle(list);
    System.out.println(list);

    // 8、sort(List<T> list) :对list集合元素进行排序

    // 9、swap(List<?> list, int i, int j) :交换集合中指定位置的元素

}

}


## File

- File导读

    1、文件:保存数据的,文件间区分,使用后缀名区分
     文件里面只能存放数据,文件不能再包含文件
     文件能进行读写操作
     怎样找到一个文件?通过文件的路径来找到文件
     文件的路径:1)、绝对路径:从盘符开始的路径
                 						e:/1.txt:绝对路径
               			 2)、相对路径,没有从盘符开始的路径
                 						jj.txt:相对路径,相对你正在操作的文件路径

     2、文件夹:管理文件或文件的
         文件夹里面可以有文件夹和文件
         **注意:**文件夹可以进行读写操作吗?不能不能绝对不能

     3、怎样区分一个路径是文件夹还是文件
         e:/pp/cc/lw.avi:表示是文件,因为有后缀名
         e:/pp/cc:表示的是文件夹

     4、一个文件或文件的组成:目录 + 名字
         e:/pp/cc/lw.avi
         e:/pp/cc/:文件的目录
         lw.avi:文件名

     5、文件或文件的操作
         1)、创建文件、删除文件、复制文件、剪切文件

## File类

File:就是表示你要操作的文件或文件夹
1、字段(属性)
 e:/pp/lw.avi;e:/cc/lw.avi
 目录分割符(一个路径里面的):/
 路径分隔符:(多个路劲之间的分割);
 pathSeparator:路径分割符,;
 separator:目录分割符, /

 2、构造方法
     1)、File(String pathname):通过传入的路径创建File对象
     2)、File(String parent, String child):在指定符目录下面,创建子目录或文件
     parent:只能表示文件夹
     child:可以是文件夹,也可以是文件
     3)、File(File parent, String child)

 3、常用的方法
     1)、表示判断方法
         isDirectory() :判断file对象是否为文件夹(目录),必须要存在
         isFile():判断file对象是否为文件
         exists():判断file对象是否存在

 2)、获取名字的方法
     getName() :获取名字
     getParent():获取符目录
     getPath():File转换为字符串的路径

 3)、创建与删除
     mkdir():只能创建一级目录 、 mkdirs() 可以创建多级目录:创建文件夹
     createNewFile():创建的是空文件
     delete():删除文件和空文件夹

 4)、将制定文件夹中所有的文件或文件都获取
     **list()**:将制定目录下所有的文件和文件夹的名字,放入一个字符串数组
     **listFiles()**:将制定目录下所有的File对象,放入一个File数组

```java
public class CollectionsDemo1 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        // 1、addAll(Collection<? super T> c, T... elements) :向集合加入指定的数据
        Collections.addAll(list,10,20,30,40,50,60); // 向list集合加入数据
        System.out.println(list);

        // 2、binarySearch(List<? extends Comparable<? super T>> list, T key):使用二分查找查询集合中元素的位置
        int i = Collections.binarySearch(list, 300);
        System.out.println(i);

        // 3、fill(List<? super T> list, T obj) :填充集合

        // 4、max(Collection<? extends T> coll) :找出集合中最大的值
        Integer max = Collections.max(list);
        System.out.println(max);

        // 5、min(Collection<? extends T> coll) :找出集合中最小的值

        // 6、reverse(List<?> list) :翻转集合元素
        Collections.reverse(list);
        System.out.println(list);

        // 7、shuffle(List<?> list):洗牌方法,打乱list集合中元素的顺序
        Collections.shuffle(list);
        System.out.println(list);

        // 8、sort(List<T> list) :对list集合元素进行排序

        // 9、swap(List<?> list, int i, int j) :交换集合中指定位置的元素

    }
}