Java泛型、IO流中的File每日一考


1.如何遍历Map的key集,value集,key-value集,使用上泛型

 1 package www.exer.collection;
 2 
 3 import java.util.*;
 4 
 5 public class MapTest {
 6     public static void main(String[] args) {
 7         Map map = new HashMap<>();
 8 
 9         //使用泛型,遍历Map中的key
10         Set keySet = map.keySet();
11         for (String key : keySet) {
12             System.out.println(key);
13         }
14 
15         //使用泛型,遍历Map中的value
16         Collection values = map.values();
17         Iterator iterator = values.iterator();
18         while (iterator.hasNext()){
19             System.out.println(iterator.next());
20         }
21 
22         //使用泛型,遍历Map中的key-value
23         Set> entrySet = map.entrySet();
24         Iterator> iterator1 = entrySet.iterator();
25         while (iterator1.hasNext()){
26             Map.Entry entry = iterator1.next();
27             String key = entry.getKey();
28             Integer value = entry.getValue();
29             System.out.println(key+"----->"+value);
30         }
31     }
32 }

2.写出使用Iterator 和 增强for 循环遍历List的代码,使用上泛型

        List list = new ArrayList<>();

        for (String s:list){
            System.out.println(s);
        }

3.提供一个方法,用于遍历获取HashMap中的所有value,并存放在List中返回。考虑上集合中泛型的使用。

  Map map1 = new HashMap<>();
@Test        
public List arrayList{

  
        ArrayList arrayList = new ArrayList<>();
        Collection value = map1.values();
        for (String str: value) {
            arrayList.add(str);
        }
        return arrayList;    
}

4.创建一个与a.txt文件同目录下的另外一个文件b.txt

 1 class Test3 {
 2     public static void main(String[] args) throws IOException {
 3         File file1 = new File("hello.txt");
 4         File file3 = new File("D:\\整理\\Exer_code\\src\\www\\hello.txt");
 5         //getParent():获取上层文件目录路径
 6         //在"D:\\整理\\Exer_code\\src\\www"路径下,hellotest.txt为子路径创建File对象(目标文件)
 7         File destfile = new File(file3.getParent(), "hellotest.txt");
 8         //创建文件"hellotest.txt",若文件存在则不创建并返回false
 9         boolean newFile = destfile.createNewFile();
10         if (newFile) {
11             //创建成功,输出语句
12             System.out.println("Created Successfully");
13         }
14     }
15 }

5.Map接口中的常用方法有哪些

增:put(key , value)

删:remove(key),remove(key , value)

改:put(key , value)

查:size(),get(key)

遍历:for,foreach,Iterator