Java 基礎(chǔ)詳解(泛型、集合、IO、反射)
計劃把 Java 基礎(chǔ)的有些部分再次看一遍,鞏固一下,下面以及以后就會分享自己再次學(xué)習(xí)的一點筆記!不是有關(guān)標題的所有知識點,只是自己覺得模糊的一些知識點。
1.對于泛型類而言,你若沒有指明其類型,默認為Object;
2.在繼承泛型類以及接口的時候可以指明泛型的類型,也可以不指明;
3.泛型也數(shù)據(jù)庫中的應(yīng)用:
寫一個 DAO 類對數(shù)據(jù)庫中的數(shù)據(jù)進行增刪改查其類型聲明為 <T> 。每張表對應(yīng)一個類,對應(yīng)每一張表實現(xiàn)一個類繼承該 DAO 類并指明 DAO 泛型為該數(shù)據(jù)表對應(yīng)的類,再實現(xiàn)一個與該表匹配的 DAO 操作類,這樣就不必在每一個數(shù)據(jù)表的操作實現(xiàn)類中去實現(xiàn)增刪改查的基本方法。例如(實際應(yīng)用中大概就是這思想,下面的舉例并不完整):
//數(shù)據(jù)表對應(yīng)的類
public class Customer{
private int id;
private String name;
...
}
//所有數(shù)據(jù)表的操作類都要實現(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ù)表操作對應(yīng)的實現(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)的調(diào)用了先出現(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.利用反射獲取方法名和屬性名,利用反射還可以獲取構(gòu)造器等其他信息
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 所對應(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 實現(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 相等時有其他的處理方法
int i = o1.getId().compareTo(o2.getId());
// 當(dāng) 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 的比較值放入?yún)?shù)中,避免 id 相等沒有其值
int i = o1.getId().compareTo(o2.getId());
// 當(dāng) 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,因為這樣可以保證流的關(guān)閉在任何時候都可以正常執(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)文件的復(fù)制(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) {
// 設(shè)置一次從目標文件中讀取多少字節(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)文件的復(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 {
// 使用緩沖流實現(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ù)制文件用到的就可以,即最后兩個
bufferedOutput.close();
bufferedInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
上面的代碼總結(jié)啥的都是自己平常練習(xí)過程中的代碼和心得,對于知識點講解覆蓋的并不全面,還望諒解。初來乍到不知道該如何去寫!
以上這篇Java 基礎(chǔ)詳解(泛型、集合、IO、反射)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解自定義SpringMVC的Http信息轉(zhuǎn)換器的使用
這篇文章主要介紹了詳解自定義SpringMVC的Http信息轉(zhuǎn)換器的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
Spring Boot 開發(fā)私有即時通信系統(tǒng)(WebSocket)
本文利用Spring Boot作為基礎(chǔ)框架,Spring Security作為安全框架,WebSocket作為通信框架,實現(xiàn)點對點聊天和群聊天2017-04-04
springsecurity記住我登錄時訪問無權(quán)限接口跳轉(zhuǎn)登錄界面的處理方案
這篇文章主要介紹了springsecurity記住我登錄時訪問無權(quán)限接口跳轉(zhuǎn)登錄界面的處理方案,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-02-02
springboot與數(shù)據(jù)庫返回數(shù)據(jù)中文亂碼
大家好,本篇文章主要講的是springboot與數(shù)據(jù)庫返回數(shù)據(jù)中文亂碼,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01
詳解Spring與Mybatis的整合方法(基于Eclipse的搭建)
這篇文章主要介紹了Spring與Mybatis的整合方法(基于Eclipse的搭建),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10

