Java 基礎(chǔ)詳解(泛型、集合、IO、反射)
計(jì)劃把 Java 基礎(chǔ)的有些部分再次看一遍,鞏固一下,下面以及以后就會(huì)分享自己再次學(xué)習(xí)的一點(diǎn)筆記!不是有關(guān)標(biāo)題的所有知識(shí)點(diǎn),只是自己覺得模糊的一些知識(shí)點(diǎn)。
1.對(duì)于泛型類而言,你若沒有指明其類型,默認(rèn)為Object;
2.在繼承泛型類以及接口的時(shí)候可以指明泛型的類型,也可以不指明;
3.泛型也數(shù)據(jù)庫中的應(yīng)用:
寫一個(gè) DAO 類對(duì)數(shù)據(jù)庫中的數(shù)據(jù)進(jìn)行增刪改查其類型聲明為 <T> 。每張表對(duì)應(yīng)一個(gè)類,對(duì)應(yīng)每一張表實(shí)現(xiàn)一個(gè)類繼承該 DAO 類并指明 DAO 泛型為該數(shù)據(jù)表對(duì)應(yīng)的類,再實(shí)現(xiàn)一個(gè)與該表匹配的 DAO 操作類,這樣就不必在每一個(gè)數(shù)據(jù)表的操作實(shí)現(xiàn)類中去實(shí)現(xiàn)增刪改查的基本方法。例如(實(shí)際應(yīng)用中大概就是這思想,下面的舉例并不完整):
//數(shù)據(jù)表對(duì)應(yīng)的類 public class Customer{ private int id; private String name; ... } //所有數(shù)據(jù)表的操作類都要實(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ù)據(jù)表操作對(duì)應(yīng)的實(shí)現(xiàn)類 public class CustomerDao extends DAO<Customer> { } //測(cè)試類 public class Test { public static void mian(String[] args) { CustomerDao cus = new CustomerDao; Cus.add(new Customer); } }
4. 靜態(tài)方法中不可以使用泛型(static)
因?yàn)閟tatic 聲明的方法或者類以及變量都是在類初始化的時(shí)候初始化,而泛型是在運(yùn)行的時(shí)候才回去初始化的,所以就出現(xiàn)了問題(后出現(xiàn)的調(diào)用了先出現(xiàn)的)。
public T t; //Error public static void show() { System.out.println(t); }
5.通配符
可以讀取聲明為通配符的集合,但不可往里寫入元素(讀的時(shí)候可以把元素都認(rèn)為是 Object,但寫的時(shí)候其聲明為 ?,不是 Object,也就是說寫什么類型都是錯(cuò)的,但可以存 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.利用反射獲取方法名和屬性名,利用反射還可以獲取構(gòu)造器等其他信息
package com.java.reflct.test; //實(shí)體類 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; //測(cè)試類 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,還以利用 對(duì)象名.getClass() 類名.class(); 獲取Class Class cla = Class.forName("com.java.reflct.test.Person"); Class cla2 = Person.class; // 獲取所有的 變量,返回?cái)?shù)組,包括私有變量 Field[] fields = cla2.getDeclaredFields(); // 遍歷變量數(shù)組 for (Field fie : fields) { System.out.println(fie+"-..-"); } // 獲取所有的方法,返回?cái)?shù)組,包括私有方法 Method[] methods = cla.getDeclaredMethods(); for (Method met : methods) { System.out.println(met); } try { // 獲取單個(gè)私有屬性 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 { // 獲取單個(gè)私有方法 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(); 獲取類的對(duì)象 Person person = (Person) cla.newInstance(); person.setId("1"); person.setName("yinyin"); person.setPhone(110); System.out.println(person + "__>>__"); try { // 執(zhí)行 person 對(duì)象的中 method 所對(duì)應(yīng)的方法 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 實(shí)現(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 的比較值放入?yún)?shù)中,使得 id 相等時(shí)有其他的處理方法 int i = o1.getId().compareTo(o2.getId()); // 當(dāng) Id 相等的時(shí)候比較名字的順序 if (i == 0) { // 給 return 添加一個(gè) - 號(hào)可以實(shí)現(xiàn) “從大到小” return o1.getName().compareTo(o2.getName()); } // Id 不相等時(shí)返回其值 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); // 利用匿名類實(shí)現(xiàn)自定義排序 /* Collections.sort(lists, new Comparator<Customer>(){ @Override public int compare(Customer o1, Customer o2) { // 將 id 的比較值放入?yún)?shù)中,避免 id 相等沒有其值 int i = o1.getId().compareTo(o2.getId()); // 當(dāng) Id 相等的時(shí)候比較名字的順序 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
讀取目標(biāo)文本文件的字節(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,因?yàn)檫@樣可以保證流的關(guān)閉在任何時(shí)候都可以正常執(zhí)行 InputStream fileStream = null; int count = 0; try { fileStream = new FileInputStream(new File("hello.txt")); // 讀取文件的下一個(gè)字節(jié) while (fileStream.read() != -1) { count++; } // 打印目標(biāo)文件的字節(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(); } } } }
實(shí)現(xiàn)文件的復(fù)制(InputStream 、OutputStream 和 Reader 、Writer)。文本文件的操作使用 Reader Writer(字符流) 去實(shí)現(xiàn),效率高。但是不可以去操作媒體文件;媒體文件使用 InputStream OutputStream 去實(shí)現(xiàn),也可以對(duì)文本文件進(jì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) { // 設(shè)置一次從目標(biāo)文件中讀取多少字節(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 的作用是防止讀取文件時(shí)最后一次其長(zhǎng)度不夠讀取被置為零,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 實(shí)現(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.利用緩沖流實(shí)現(xiàn)文件的復(fù)制操作,效率更高
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 { // 使用緩沖流實(shí)現(xiàn)文件的復(fù)制 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 { // 只需關(guān)閉復(fù)制文件用到的就可以,即最后兩個(gè) bufferedOutput.close(); bufferedInput.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
上面的代碼總結(jié)啥的都是自己平常練習(xí)過程中的代碼和心得,對(duì)于知識(shí)點(diǎn)講解覆蓋的并不全面,還望諒解。初來乍到不知道該如何去寫!
以上這篇Java 基礎(chǔ)詳解(泛型、集合、IO、反射)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)世界上最快的排序算法Timsort的示例代碼
Timsort?是一個(gè)混合、穩(wěn)定的排序算法,簡(jiǎn)單來說就是歸并排序和二分插入排序算法的混合體,號(hào)稱世界上最好的排序算法。本文將詳解Timsort算法是定義與實(shí)現(xiàn),需要的可以參考一下2022-07-07SpringBoot動(dòng)態(tài)定時(shí)任務(wù)實(shí)現(xiàn)完整版
最近有幸要開發(fā)個(gè)動(dòng)態(tài)定時(shí)任務(wù),這里簡(jiǎn)單再梳理一下,下面這篇文章主要給大家介紹了關(guān)于SpringBoot動(dòng)態(tài)定時(shí)任務(wù)實(shí)現(xiàn)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02Spring Boot 中該如何防御計(jì)時(shí)攻擊
這篇文章主要介紹了Spring Boot 中該如何防御計(jì)時(shí)攻擊,幫助大家更好的使用spring boot框架,感興趣的朋友可以了解下2020-09-09java學(xué)習(xí)之理解自動(dòng)拆裝箱特性
這篇文章主要介紹java自動(dòng)拆裝箱特性以及java自動(dòng)拆裝箱的應(yīng)用,有需要的朋友可以借鑒參考下,希望可以有所幫助,祝大家早日升職加薪2021-09-09SpringBoot項(xiàng)目中使用OkHttp獲取IP地址的示例代碼
OkHttp?是一個(gè)由?Square?開發(fā)的高效、現(xiàn)代的?HTTP?客戶端庫,用于?Android?和?Java?應(yīng)用程序,它支持?HTTP/2?和?SPDY?等現(xiàn)代網(wǎng)絡(luò)協(xié)議,并提供了多種功能和優(yōu)化,本文給大家介紹了SpringBoot項(xiàng)目中如何獲取IP地址,需要的朋友可以參考下2024-08-08如何使用Collections.reverse對(duì)list集合進(jìn)行降序排序
這篇文章主要介紹了Java使用Collections.reverse對(duì)list集合進(jìn)行降序排序,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11