Java 基礎詳解(泛型、集合、IO、反射)
計劃把 Java 基礎的有些部分再次看一遍,鞏固一下,下面以及以后就會分享自己再次學習的一點筆記!不是有關標題的所有知識點,只是自己覺得模糊的一些知識點。
1.對于泛型類而言,你若沒有指明其類型,默認為Object;
2.在繼承泛型類以及接口的時候可以指明泛型的類型,也可以不指明;
3.泛型也數(shù)據庫中的應用:
寫一個 DAO 類對數(shù)據庫中的數(shù)據進行增刪改查其類型聲明為 <T> 。每張表對應一個類,對應每一張表實現(xiàn)一個類繼承該 DAO 類并指明 DAO 泛型為該數(shù)據表對應的類,再實現(xiàn)一個與該表匹配的 DAO 操作類,這樣就不必在每一個數(shù)據表的操作實現(xiàn)類中去實現(xiàn)增刪改查的基本方法。例如(實際應用中大概就是這思想,下面的舉例并不完整):
//數(shù)據表對應的類
public class Customer{
private int id;
private String name;
...
}
//所有數(shù)據表的操作類都要實現(xiàn)的 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;
}
//數(shù)據表操作對應的實現(xiàn)類
public class CustomerDao extends DAO<Customer> {
}
//測試類
public class Test {
public static void mian(String[] args) {
CustomerDao cus = new CustomerDao;
Cus.add(new Customer);
}
}
4. 靜態(tài)方法中不可以使用泛型(static)
因為static 聲明的方法或者類以及變量都是在類初始化的時候初始化,而泛型是在運行的時候才回去初始化的,所以就出現(xiàn)了問題(后出現(xiàn)的調用了先出現(xiàn)的)。
public T t;
//Error
public static void show() {
System.out.println(t);
}
5.通配符
可以讀取聲明為通配符的集合,但不可往里寫入元素(讀的時候可以把元素都認為是 Object,但寫的時候其聲明為 ?,不是 Object,也就是說寫什么類型都是錯的,但可以存 null),例如
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 的遍歷
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.利用反射獲取方法名和屬性名,利用反射還可以獲取構造器等其他信息
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;
// 獲取所有的 變量,返回數(shù)組,包括私有變量
Field[] fields = cla2.getDeclaredFields();
// 遍歷變量數(shù)組
for (Field fie : fields) {
System.out.println(fie+"-..-");
}
// 獲取所有的方法,返回數(shù)組,包括私有方法
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 {
// 執(zhí)行 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 實現(xiàn)集合的自定義排序)
注意區(qū)分 Collections (集合的處理類)和 Collection (集合基類)
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 的比較值放入參數(shù)中,使得 id 相等時有其他的處理方法
int i = o1.getId().compareTo(o2.getId());
// 當 Id 相等的時候比較名字的順序
if (i == 0) {
// 給 return 添加一個 - 號可以實現(xiàn) “從大到小”
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);
// 利用匿名類實現(xiàn)自定義排序
/*
Collections.sort(lists, new Comparator<Customer>(){
@Override
public int compare(Customer o1, Customer o2) {
// 將 id 的比較值放入參數(shù)中,避免 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
讀取目標文本文件的字節(jié)數(shù)
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 中出現(xiàn)的異常最好都使用 try-catch 包裹起來,不要 throw,因為這樣可以保證流的關閉在任何時候都可以正常執(zhí)行
InputStream fileStream = null;
int count = 0;
try {
fileStream = new FileInputStream(new File("hello.txt"));
// 讀取文件的下一個字節(jié)
while (fileStream.read() != -1) {
count++;
}
// 打印目標文件的字節(jié)數(shù)
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();
}
}
}
}
實現(xiàn)文件的復制(InputStream 、OutputStream 和 Reader 、Writer)。文本文件的操作使用 Reader Writer(字符流) 去實現(xiàn),效率高。但是不可以去操作媒體文件;媒體文件使用 InputStream OutputStream 去實現(xiàn),也可以對文本文件進行操作,但是沒有字符流高效。
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) {
// 設置一次從目標文件中讀取多少字節(jié)
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() 返回讀入緩沖區(qū)的字節(jié)總數(shù)
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 實現(xiàn)
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.利用緩沖流實現(xiàn)文件的復制操作,效率更高
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 {
// 使用緩沖流實現(xiàn)文件的復制
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、反射)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java實現(xiàn)世界上最快的排序算法Timsort的示例代碼
Timsort?是一個混合、穩(wěn)定的排序算法,簡單來說就是歸并排序和二分插入排序算法的混合體,號稱世界上最好的排序算法。本文將詳解Timsort算法是定義與實現(xiàn),需要的可以參考一下2022-07-07
SpringBoot動態(tài)定時任務實現(xiàn)完整版
最近有幸要開發(fā)個動態(tài)定時任務,這里簡單再梳理一下,下面這篇文章主要給大家介紹了關于SpringBoot動態(tài)定時任務實現(xiàn)的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02
SpringBoot項目中使用OkHttp獲取IP地址的示例代碼
OkHttp?是一個由?Square?開發(fā)的高效、現(xiàn)代的?HTTP?客戶端庫,用于?Android?和?Java?應用程序,它支持?HTTP/2?和?SPDY?等現(xiàn)代網絡協(xié)議,并提供了多種功能和優(yōu)化,本文給大家介紹了SpringBoot項目中如何獲取IP地址,需要的朋友可以參考下2024-08-08
如何使用Collections.reverse對list集合進行降序排序
這篇文章主要介紹了Java使用Collections.reverse對list集合進行降序排序,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

