Java 基础详解(泛型、集合、IO、反射)

时间:2022-11-30 09:22:16

计划把 Java 基础的有些部分再次看一遍,巩固一下,下面以及以后就会分享自己再次学习的一点笔记!不是有关标题的所有知识点,只是自己觉得模糊的一些知识点。

1.对于泛型类而言,你若没有指明其类型,默认为Object;

2.在继承泛型类以及接口的时候可以指明泛型的类型,也可以不指明;

3.泛型也数据库中的应用:

写一个 DAO 类对数据库中的数据进行增删改查其类型声明为 <T> 。每张表对应一个类,对应每一张表实现一个类继承该 DAO 类并指明 DAO 泛型为该数据表对应的类,再实现一个与该表匹配的 DAO 操作类,这样就不必在每一个数据表的操作实现类中去实现增删改查的基本方法。例如(实际应用中大概就是这思想,下面的举例并不完整):

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
//数据表对应的类
public class Customer{
 private int id;
 private String name;
 ...
}
 
//所有数据表的操作类都要实现的 DAO 基类
public class DAO<T> {
 //增
 public void add(T t) {
 
 
}
 
public T get(int index) {
 //查
 return null;
}
 
public void delete() {
 //删
 
}
 
public List<T> getForList(int index) {
 //查
 return null;
}
 
//数据表操作对应的实现类
public class CustomerDao extends DAO<Customer> {
    
}
 
//测试类
public class Test {
 public static void mian(String[] args) {
 CustomerDao cus = new CustomerDao;
 Cus.add(new Customer);
 }
}

4. 静态方法中不可以使用泛型(static)

因为static 声明的方法或者类以及变量都是在类初始化的时候初始化,而泛型是在运行的时候才回去初始化的,所以就出现了问题(后出现的调用了先出现的)。

?
1
2
3
4
5
public T t;
 //Error
 public static void show() {
  System.out.println(t);
}

5.通配符

可以读取声明为通配符的集合,但不可往里写入元素(读的时候可以把元素都认为是 Object,但写的时候其声明为 ?,不是 Object,也就是说写什么类型都是错的,但可以存 null),例如

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Public void testList() {
 List<String> strList = new ArrayList<>();
 strList.add(“Hello”);
 strList.add(“World”);
 
 //correct
 List<?> list = strList;
 
 //error
 list.add(“hi”);
 list.add(123);
 //correct
 list.add(null);
}

6.集合Map 的遍历

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.java.map.test;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class MapEntry {
 
 public static void main(String[] args) {
  Map<Integer, String> map = new HashMap<>();
  map.put(1, "a");
  map.put(2, "b");
  map.put(3, "c");
  map.put(4, "d");
  map.put(5, "e");
  // 得到 map 所有键的集合
  Set<Integer> keys = map.keySet();
 
  for (Integer key : map.keySet()) {
   System.out.println(map.get(key));
  }
 
  // 利用迭代器 遍历
  Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
 
  while (it.hasNext()) {
   Map.Entry<Integer, String> entry = it.next();
   System.out.println(entry.getKey() + " -> " + entry.getValue());
  }
 
  // 第三种
  for (Map.Entry<Integer, String> entry : map.entrySet()) {
   System.out.println(entry.getValue());
  }
 
  // 遍历所有的 value 值
  Collection<String> values = map.values();
 
  for (String val : values) {
   System.out.println(val + ">>-");
  }
 
  Iterator<String> i = values.iterator();
  while (i.hasNext()) {
   System.out.println(i.next() + "-->");
  }
 
  List<String> lists = new ArrayList<>();
  lists.add("1");
  lists.add("2");
  lists.add("3");
  lists.add("4");
 
  Iterator<String> it2 = lists.iterator();
 
  while (it2.hasNext()) {
   System.out.println(it2.next());
  }
  
  Collections.reverse(lists);
  Iterator<String> it3 = lists.iterator();
//  Comparator comparator = new
  
  
  while (it3.hasNext()) {
   System.out.println(it3.next() + "<->");
  }
 }
}

7.利用反射获取方法名和属性名,利用反射还可以获取构造器等其他信息

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package com.java.reflct.test;
 
//实体类
public class Person {
 
 private String id;
 
 private String name;
 
 public int phone;
 
 public void setId(String id) {
  this.id = id;
 }
 
 public String getId() {
  return id;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public String getName() {
  return name;
 }
 
 public void setPhone(int phone) {
  this.phone = phone;
 }
 
 public int getPhone() {
  return phone;
 }
 
 private void print() {
  System.out.println("your id is " + id + ", your name is " + name + ", your phone is " + phone + "!");
 }
 
 @Override
 public String toString() {
  return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]";
 }
}
 
package com.java.reflct.test;
//测试类
 
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class TestReflect {
 
 public static void main(String[] args) {
  try {
//   通过 Class.forName("全类名"); 获取 Class,还以利用 对象名.getClass() 类名.class(); 获取Class
   Class cla = Class.forName("com.java.reflct.test.Person");
   Class cla2 = Person.class;
   
//   获取所有的 变量,返回数组,包括私有变量
   Field[] fields = cla2.getDeclaredFields();
//   遍历变量数组
   for (Field fie : fields) {
    System.out.println(fie+"-..-");
   }
   
//   获取所有的方法,返回数组,包括私有方法
   Method[] methods = cla.getDeclaredMethods();
   
   for (Method met : methods) {
    System.out.println(met);
   }
   
   try {
//    获取单个私有属性
    Field field = cla.getDeclaredField("id");
//    打破封装
    field.setAccessible(true);
    System.out.println(field + "<<>>");
   } catch (NoSuchFieldException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   Method method = null;
   
   try {
//    获取单个私有方法
    method = cla.getDeclaredMethod("print");
//    打破封装
    method.setAccessible(true);
    System.out.println(method + ">><<");
   } catch (NoSuchMethodException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   try {
//    通过cla.newInstance(); 获取类的对象
    Person person = (Person) cla.newInstance();
    person.setId("1");
    person.setName("yinyin");
    person.setPhone(110);
    
    System.out.println(person + "__>>__");
    try {
//     执行 person 对象的中 method 所对应的方法
     method.invoke(person);
    } catch (IllegalArgumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (InvocationTargetException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   } catch (InstantiationException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   } catch (IllegalAccessException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
   
   
  } catch(ClassNotFoundException e) {
   System.out.println("There is no class " + e);
  }
 }
}

8.Comparator  类的使用(利用  Comparator  实现集合的自定义排序)

注意区分 Collections (集合的处理类)和 Collection (集合基类)

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.java.collection.test;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
 
/*
 * Collections 是 Collection 的操作类
 */
 
public class CollectionComparator {
 
 public static void main(String[] args) {
  
  Comparator<Customer> com = new Comparator<Customer>(){
 
   @Override
   public int compare(Customer o1, Customer o2) {
//    将 id 的比较值放入参数中,使得 id 相等时有其他的处理方法
    int i = o1.getId().compareTo(o2.getId());
    
//    当 Id 相等的时候比较名字的顺序
    if (i == 0) {
//     给 return 添加一个 - 号可以实现 “从大到小”
     return o1.getName().compareTo(o2.getName());
    }
//         Id 不相等时返回其值 
         return i;
   }
  };
  
  List<Customer> lists = new ArrayList<>();
  lists.add(new Customer("yinyin", "110", 1001));
  lists.add(new Customer("zhao", "10086", 1002));
  lists.add(new Customer("ls", "10010", 1001));;
  
  Collections.sort(lists, com);
  
//  利用匿名类实现自定义排序
  /*
  Collections.sort(lists, new Comparator<Customer>(){
 
   @Override
   public int compare(Customer o1, Customer o2) {
//    将 id 的比较值放入参数中,避免 id 相等没有其值
    int i = o1.getId().compareTo(o2.getId());
    
//    当 Id 相等的时候比较名字的顺序
    if (i == 0) {
     return o1.getName().compareTo(o2.getName());
    }
    return i;
   }
  });
  */
 //利用迭代器遍历集合
  Iterator<Customer> it = lists.iterator();
  while(it.hasNext()) {
   System.out.println(it.next());
  }
  
 }
}

9.IO

读取目标文本文件的字节数

?
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
30
31
32
33
34
35
36
37
38
39
package com.java.io.file.test;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
public class MyIoTest {
 
 public static void main(String[] args) {
  
//  在 IO 中出现的异常最好都使用 try-catch 包裹起来,不要 throw,因为这样可以保证流的关闭在任何时候都可以正常执行
  InputStream fileStream = null;
  int count = 0;
  try {
   fileStream = new FileInputStream(new File("hello.txt"));
//   读取文件的下一个字节
   while (fileStream.read() != -1) {
    count++;
   }
//   打印目标文件的字节数
   System.out.println(count);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    fileStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

实现文件的复制(InputStream 、OutputStream 和 Reader 、Writer)。文本文件的操作使用 Reader Writer(字符流) 去实现,效率高。但是不可以去操作媒体文件;媒体文件使用 InputStream OutputStream 去实现,也可以对文本文件进行操作,但是没有字符流高效。

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.java.io.file.test;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class CopyFile {
 
 public static void main(String[] args) {
//  设置一次从目标文件中读取多少字节
  byte[] buffer = new byte[1024];
 
  int len = 0;
  File file = new File("C:/Users/lenovo/Desktop/123.wmv");
  InputStream fileInput = null;
  OutputStream fileOut = null;
 
  try {
   fileInput = new FileInputStream(file);
   fileOut = new FileOutputStream(new File("C:/Users/lenovo/Desktop/trave2.wmv"));
 
//   len 的作用是防止读取文件时最后一次其长度不够读取被置为零,read() 返回读入缓冲区的字节总数
   while ((len = fileInput.read(buffer)) != -1) {
    fileOut.write(buffer, 0, len);
   }
   System.out.println("SUCC");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    fileOut.close();
    fileInput.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
}
 
 
 
 
 
//利用 Reader Writer 实现
package com.java.io.file.test;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
 
public class ReaderWriter {
 
 public static void main(String[] args) {
  File file = new File("hello.txt");
  int len = 0;
  Reader fileReader = null;
  Writer fileWriter = null;
  char[] ch = new char[125];
  
  try {
   fileReader = new FileReader(file);
   fileWriter = new FileWriter(new File("world.txt"));
   
   while((len = fileReader.read(ch)) != -1) {
    fileWriter.write(ch, 0, len);
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    fileWriter.close();
    fileReader.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

10.利用缓冲流实现文件的复制操作,效率更高

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.java.io.file.test;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class TestBufferedCopy {
// 使用缓冲流实现文件的复制
 public static void main(String[] args) {
  
  int len = 0;
  byte[] buffer = new byte[2048];
  
  File file = new File("C:/Users/lenovo/Desktop/123.rmvb");
  InputStream inputFile = null;
  OutputStream outputFile = null;
 
  BufferedInputStream bufferedInput = null;
  BufferedOutputStream bufferedOutput = null;
  
  try {
   inputFile = new FileInputStream(file);
   outputFile = new FileOutputStream("C:/Users/lenovo/Desktop/456.rmvb");
   
   bufferedInput = new BufferedInputStream(inputFile);
   bufferedOutput = new BufferedOutputStream(outputFile);
   
   while((len = bufferedInput.read(buffer)) != -1) {
    bufferedOutput.write(buffer, 0, len);
   }
   
   System.out.println("SUCC");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
//    只需关闭复制文件用到的就可以,即最后两个
    bufferedOutput.close();
    bufferedInput.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

上面的代码总结啥的都是自己平常练习过程中的代码和心得,对于知识点讲解覆盖的并不全面,还望谅解。初来乍到不知道该如何去写!

以上这篇Java 基础详解(泛型、集合、IO、反射)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/bgzyy/archive/2017/10/30/7752095.html