java 基礎程式碼
阿新 • • 發佈:2019-01-07
some java code is very important ,so I describe them at there!
/*
this is Single----------------Single------------------------
*/
class Single{
private static Single s = null;//
private Single(){
}
public static Single getSingle(){
if(s == null) s = new Single();
return s;
}
}
class Single2 {
Single2 s = new Single2();
enum Single{s};
}
---------------------------------------------------------------------------------------
//this is javaCodeConventions
/*
* Classname:MyjavaCodeConventions
*
* Version information:0.0
*
* Date:2014-2-25
*
* Copyright notice
*/
/*
* 命名規範:命名規範使程式更易讀,從而更易於理解。它們也可以提供一些有關識別符號功能的資訊,
* 以助於理解程式碼,例如,不論它是一個常量,包,還是類。
* 程式規範:使易於理解和維護,使效率高,儘量避免無關程式碼
* 包:com.snc.javacode
* 類/介面:MyClass、MyInterface
* 方法:myMethod(),run()
* 變數:短而且易於記憶 int i,j,k ; char c ,d , e;float fvar;
* 例項變數: int _employeeId;String _name;Customer _customer;
* 常量:大寫與下劃線構成 static final int MIN_WIDTH = 4;
* 若沒有足夠理由,不要把例項或類變數宣告為公有。通常,例項變數無需顯式的設定(set)和獲取(gotten),通常這作為方法呼叫的邊緣效應 (side effect)而產生。
* 一個具有公有例項變數的恰當例子,是類僅作為資料結構,沒有行為。亦即,若你要使用一個結構(struct)而非一個類(如果java支援結構的話),
* 那麼把類的例項變數宣告為公有是合適的。
*
*/
package snc;
/**
* to describle the java code conventions
*
* @version 0
* @author Firstname:zjm Lastname:zjm
*
* 文件註釋描述Java的類、介面、構造器,方法,以及欄位(field)
*/
// @註解
/*
* 該註釋應包含任何有關整個類或介面的資訊,而這些資訊又不適合作為類/介面文件註釋。程式編寫:縮排(製表符,if縮排8字元),換行規則(行長度<=70)
* 註釋:文件註釋,實現註釋,註釋不應該包括特殊字元,太多的註釋顯示出程式碼的低質量
*/
/*
* 塊註釋通常用於提供對檔案,方法,資料結構和演算法的描述。 塊註釋被置於每個檔案的開始處以及每個方法之前。它們也可以被用於其他地方,
* 比如方法內部。在功能和方法內部的塊註釋應該和它們所描述的程式碼具有一樣的縮排格式。
*/
/* 如果一個註釋不能在一行內寫完,就該採用塊註釋 */
// 用於註釋多餘的程式碼塊和行尾註釋
public class MyjavaCodeConventions {
/*
* 類的(靜態)變數 首先是類的公共變數,隨後是保護變數,再後是包一級別的變數 (沒有訪問修飾符,access modifier),最後是私有變數。
* 例項變數 首先是公共級別的,隨後是保護級別的,再後是包一級別的(沒有訪問修飾符), 最後是私有級別的。
* 儘量在宣告區域性變數的同時初始化。唯一不這麼做的理由是變數的初始值依賴於某些先前發生的計算只在程式碼塊的開始處宣告變
*/
public static int ivar = 1;
protected boolean bvar = false;
AnotherClass anotherClass = new AnotherClass();
private AnotherClass anoterClass2 = new AnotherClass();
private int b;
/*
* 構造方法
*/
@SuppressWarnings("static-access")
public MyjavaCodeConventions() {
anotherClass = this.anoterClass2;
b = this.ivar;
}
public MyjavaCodeConventions(boolean bvar) {
super();
this.bvar = bvar;
}
/*
* 這些方法應該按功能,而非作用域或訪問許可權,分組。 一個私有的類方法可以置於兩個公有的例項方法之間。其目的是為了更便於閱讀和理解程式碼。
* 斷開程式碼(,後面,操作符前面)
*/
}
class AnotherClass {
}
============================================
test Scanner and Random System
============================================
Random r = new Random();
Scanner s = new Scanner(System.in);
int []a = new int[3];
int []b = new int [10];
for(int i = 0;i < a.length;i++) {
a[i] = s.nextInt();
}
Arrays.sort(a);
int s = (int)n1 + (int)(Math.random()*(n2-n1));
char c = (char)(c1+Math.random()*(c2 - c1 +1));
================================================
some IO util: ------IPO-------
================================================
//各種流之間的巢狀關係
new DataInputStream(new BufferedInputStream(new SequenceInputStream(new FileInputStream("d:\\1"), f1)));
new DataInputStream(new BufferedInputStream(new FileInputStream("d:\\1")));
new DataInputStream(new FileInputStream("d:\\1"));
new ObjectInputStream(new BufferedInputStream(new FileInputStream("d:\\1")));
new ObjectInputStream(new FileInputStream("d:\\1"));
public class IoUtil {
public static void close(InputStream is) {
if (is != null) {
try {
is.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
public static void close(OutputStream os) {
if (os != null) {
try {
os.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
/*讀取檔案+中的檔案,並顯示到面板*/
public static void readFile(String catalog,String fileName){
int b = 0;
byte buffer[] = new byte[2500];
try{
File f = new File(catalog,fileName);
FileInputStream file = new FileInputStream(f);
b = file.read(buffer,0,2500);
try{
String str = new String(buffer,0,b,"Default");
System.out.println(str);
}catch(UnsupportedEncodingException u){
System.out.println("the encoding was not found: "+u);
}
}catch(IOException e){
System.out.println("File is read Error");
}
}
/*複製檔案*/
public static void copyFile(File sorceFile, File targetFile)
throws IOException {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(new FileInputStream(sorceFile));
os = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] b = new byte[1024 * 5];
int len;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
os.flush(); // 關閉連結前需要重新整理緩衝區
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 通過抽取公共方法形成工具類,簡化程式,提高程式碼重用
IoUtil.close(is);
IoUtil.close(os);
}
}
public static void fileReadWritetofile(File inFile,File outFile) throws IOException{
InputStream is = null;
OutputStream os = null;
try{
is = new BufferedInputStream(new FileInputStream(inFile),4*1024);
os = new BufferedOutputStream(new FileOutputStream(outFile),4*1024);
int len = 0;
byte[]bytes = new byte[4*1024];
while((len = is.read(bytes))!= -1){
os.write(bytes,0,len);
}
os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(is);
IoUtil.close(os);
}
}
/* 複製資料夾*/
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目標目錄
(new File(targetDir)).mkdirs();
// 獲取原始檔夾當前下的檔案或目錄
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 原始檔
File sourceFile = file[i];
// 目標檔案
File targetFile = new File(
new File(targetDir).getAbsolutePath() + File.separator
+ file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 準備複製的原始檔夾
String dir1 = sourceDir + "/" + file[i].getName();
// 準備複製的目標資料夾
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
/* the object serializable */
// 持久化物件,將物件寫入到文 件中
public static void writeObject(Object obj, File file) {
// 寫入順序 obj(Object)->oos(ObjectOutStream)--byte[]->fos(FileOutputStream)->file(File)
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(file); // 支援二進位制的文 件寫入流
oos = new ObjectOutputStream(fos); // 將物件流和文
// 件流關聯起來
oos.writeObject(obj);// 將物件轉換為位元組流,並寫入到文 件中
oos.flush();// 將快取中內容刷到介質中
} catch (IOException e) {
e.printStackTrace();
}finally{
// 通過抽取公共方法形成工具類,簡化程式,提高程式碼重用
IoUtil.close(fos);
}
}
// 讀取物件,從文 件中恢復物件
public static Object readObject(File file) {
// 流處理過程 file(File)->fis(FileInputStream)->ois(ObjectInputStram)->object(Object)
Object obj = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(file); //用二進位制流讀取文 件內容
ois = new ObjectInputStream(fis); //將二進位制流提供給物件流解析
obj = ois.readObject(); //根據文 件內容恢復物件
//ois.close();// 關閉文 件流
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 通過抽取公共方法形成工具類,簡化程式,提高程式碼重用
IoUtil.close(ois);
}
return obj;
}
//// 建立序列化物件
//Person person = new Person();
//person.setId(1);
//person.setName("張三");
//person.setPwd("1998998");//pwd 為非序列化元素
//// 物件寫入的文 件 new file ——》寫入--》恢復物件
//File file = new File("c:/object.serperson");
//IoUtil.writeObject(person, file);
//
//// 從序列化文 件中恢復物件
//Person result = (Person)IoUtil.readObject(file);
//System.out.println("id:\t " + result.getId() + " name: "
//+ result.getName() + " \tpwd: \t" + result.getPwd());
////id: 1 name: 張三 pwd: null
public static void printDataoutputstreamTofile(String s,File f)throws IOException{
DataOutputStream ds = null;
try{
ds = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
ds.writeUTF(s);
ds.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(ds);
}
}
public static void printWriter(String s,File f)throws IOException{
PrintWriter p = null;
try{
p = new PrintWriter(f);
p.println(s);
}catch(IOException e){
e.printStackTrace();
}finally{
if (p != null) {
p.close();// 關閉文 件流
}
}
}
public static void testWriter(char[]chars, File f)throws Exception{
FileWriter w = null;
try{
w = new FileWriter(f);
w.write(chars);
w.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
if (w != null) {
try {
w.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
}
public static void fileReadWritetofile(File inFile,File outFile) throws IOException{
InputStream is = null;
OutputStream os = null;
try{
is = new BufferedInputStream(new FileInputStream(inFile),4*1024);
os = new BufferedOutputStream(new FileOutputStream(outFile),4*1024);
int len = 0;
byte[]bytes = new byte[4*1024];
while((len = is.read(bytes))!= -1){
os.write(bytes,0,len);
}
os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(is);
IoUtil.close(os);
}
}
public static void writeGBK(){
OutputStreamWriter osw = null;
try{
osw = new OutputStreamWriter( new FileOutputStream("c:\\gbk.txt"),"GBK");
osw.write("abc");
osw.write("釋出");
osw.flush();
}catch(IOException e){
System.out.println(e);
}finally{
if (osw != null) {
try {
osw.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
}
public static void readGBK(){
try{
BufferedReader reader
= new BufferedReader(new InputStreamReader(new FileInputStream("C:\\gbk.txt"),"GBK"));
String s;
while((s = reader.readLine())!=null){
System.out.println("read: "+s);
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void readUTF8(){
try{
BufferedReader reader
= new BufferedReader(new InputStreamReader(new FileInputStream("c:\\gbk.txt"),"UTF-8"));
String s;
while((s = reader.readLine())!=null){
System.out.println("read: "+s);
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
================================================
Exception
================================================
try
{
是必須的
}
catch ()
{
可有多個
}
finally 程式碼必須得到執行,try與finally最多一個
java.lang.Object
|
-|----.Throwable
-|----.Error
-|----.Exception
-|----.IOException
-|----.RuntimeException
-|----.ArithmeticException
-|----.ArrayIndexOutOfBoundsException
-|----.NumberFormatException
//Account //存錢//取款throws InsufficientFundsException(自定義異常)
public class Account {
private String name; //取款人姓名
private double balance; //餘額
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
//存錢
public void deposite(double dAmount) {
if(dAmount > 0.0) balance += dAmount;
}
//取款
public void withdrawal(double dAmount) throws InsufficientFundsException {
if(dAmount > balance) {
String message = "取款金額超過了賬戶的當前餘額";
throw new InsufficientFundsException(message, this, dAmount);
}
balance = balance - dAmount;
}
}
/**
* 首先自定義異常 類
* @author Administrator
*
*/
public class InsufficientFundsException extends Exception {
private Account account; //賬號
private double excepAmount; //異常 的取款金額
//message引數是傳給Exception類的
public InsufficientFundsException(String message, Account account, double dAmount) {
super(message);
this.account = account;
this.excepAmount = dAmount;
}
public Account getAccount() {
return account;
}
public double getExcepAmount() {
return excepAmount;
}
}
//Client
public class Client {
public static void main(String[] args) {
//初始化一個賬號
Account account = new Account("張三", 1000.0);
//存錢
account.deposite(100);
//查詢餘額
System.out.println("當前餘額是: " + account.getBalance());
//取款(處理業務的try)
try{
account.withdrawal(50);
} catch(InsufficientFundsException e) {
e.printStackTrace(); //這是簡單的異常 處理方式,直接將錯誤資訊輸出到控制檯。實際專案中會使用log4j將鉕誤資訊記錄到日 志中,以便以後進行統計分析
}
//查詢餘額
System.out.println("取款50後的當前餘額是: " + account.getBalance());
try{
account.withdrawal(10000);
} catch(InsufficientFundsException e) {
e.printStackTrace(); //這是簡單的異常 處理方式,直接將錯誤資訊輸出到控制檯。實際專案中會使用log4j將鉕誤資訊記錄到日 志中,以便以後進行統計分析
}
}
}
static int test(){
int x = 1;
try{
return x;
}
finally{
++x;
System.out.print("x=");
//return x; //無返回1,有返回2
}
}
==================================================
java集合框架(對外的介面,介面的實現,集合的演算法) Collection Map
==================================================
interface.java.util.Collection
|
-|----.List
-|----.Set
-|----.SortedSet
interface.java.util.Map
|
-|----.SortedMap
------------------------------------------List:ArrayList---------------------------------------------
System.out.println("這是ArrayListd的例子:add(),get(),set(),remove(),和兩種遍歷方式:");
String str[] = {"ab","cd","er","gh","ij"};
ArrayList list = new ArrayList();
list.add("litter are: ");
for(int i = 0;i < str.length; i++){
list.add(str[i]);
}
list.add(",that's all");
System.out.println("the arraylist is: ");
for(int i = 0;i < list.size();i++){
System.out.print(list.get(i));
}
System.out.println();
//list.remove(1);
list.set(4,"AB");//設定陣列第4個為AB
Iterator iter = list.iterator();
while(iter.hasNext()){
Object temp = iter.next();
System.out.print(temp);
}
System.out.println();
}
---------------------------------------------------------------------------------------
public static void main(String[] args) {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
list.add("g");
Iterator iter = list.iterator();
while(iter.hasNext()) {
String node = (String)iter.next();
System.out.println(node);
iter.remove();
//遍歷集合時不要刪除集合中的元素,這樣通常 會引發異常
//list.remove(6);
}
}
---------------------------------------------------------------------------------------
public static void main(String[] args) {
List list = new ArrayList();
//基本操作
Person person = new Person();
person.setName("person");
list.add(person);
System.out.println(list.size());
System.out.println(list.isEmpty());
/*
* 與索引下載有關的方法
*/
Person person1 = new Person();
person1.setName("person1");
list.add(0, person1); //將person1插入到集合的第一個位置
Person person2 = new Person();
person2.setName("person2");
list.set(0, person2); //將person2替換到集合的第一個位置
System.out.println(list.indexOf(person2)); //確定person2的下標
/*
* 支援下標索引迴圈和迭代子迴圈
*/
//遍歷 類似於陣列使用下標遍歷,下標從0開始
for(int i = 0; i < list.size(); i++) {
Person temp = (Person)list.get(i);
System.out.println(temp.getName());
}
//迭代子迴圈 這是另一種對集合遍歷的方式
Iterator iter = list.iterator();
while(iter.hasNext()) {
Person temp = (Person)iter.next();
System.out.println(temp.getName());
}
}
---------------------------------------LinkedList------------------------------------------------
package com.job.collection.collection_map;
/*
* Collection
* |_ _ _Set
* | |_ _SortedSet
* | | |__TreeSet
* | |__HashSet
* |
* |_ _ _List
* |___ArrayList
* |___LinkedList
* 對集合框架的理解,各個結合間的區別,使用
*/
public static void main(String[] args) {
//棧實現 先進後出、後進先出
LinkedList stack = new LinkedList();
stack.push("a"); //入棧
stack.push("b");
System.out.println(stack.size()); //棧大小
String temp = (String)stack.pop(); //出棧
System.out.println("temp: " + temp); //b
//佇列實現 先進先出
LinkedList queue = new LinkedList();
queue.addLast("a"); //入佇列
queue.addLast("b");
queue.addLast("c");
System.out.println(queue.size()); //佇列大小
while(queue.isEmpty()){
String temp1 = (String)queue.poll(); //出佇列
System.out.println("temp1: " + temp1); //a
}
}
-------------------------Collection----------------------------
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class TestCollection {
//單 個集合元素的操作
public void single() {
Collection coll = new ArrayList();
Person person = new Person();
System.out.println(coll.add(person)); //增加第一個元素,返回true
System.out.println(coll.size()); //此時集合大小為1
System.out.println(coll.isEmpty()); //判斷集合是否為空
System.out.println(coll.contains(person)); //判斷集合是否包含指定物件
System.out.println("----------------------------------");
System.out.println(coll.remove(person)); //刪除元素,返回true
System.out.println(coll.size()); //此時集合大小為0
System.out.println(coll.isEmpty()); //判斷集合是否為空
System.out.println(coll.contains(person)); //判斷集合是否包含指定物件
}
//多個集合地素的操作
public void mutli() {
//構造集合物件
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
Person person3 = new Person();
person3.setName("person3");
Person person4 = new Person();
person4.setName("person4");
Person person5 = new Person();
person5.setName("person5");
Person person6 = new Person();
person6.setName("person6");
String str = "Hello";
//構造第一個集合
Collection coll = new ArrayList();
coll.add(person1);
coll.add(person2);
coll.add(person3);
//構造第二個集合
Collection coll2 = new ArrayList();
coll2.add(person4);
coll2.add(person5);
coll2.add(person6);
coll2.add(str);
/*
* 集合間操作
*/
coll.addAll(coll2); //將第二個集合加入到第一個集合中
System.out.println(coll.size()); //此時集合大小為7
System.out.println(coll.containsAll(coll2)); //判斷集合是否包含指定集合中的所有物件
System.out.println("----------------------------------");
coll.removeAll(coll2); //刪除指定集合中的所有物件
System.out.println(coll.size()); //此時集合大小為3
coll.retainAll(coll2); //刪除coll中所有不被coll2包含的集合元素
System.out.println(coll.size()); //此時集合大小為0
coll.add(person1);
coll.add(person2);
coll.add(person3);
coll.clear();
System.out.println(coll.size()); //此時集合大小為0
System.out.println("----------------------------------");
/*
* 遍歷集合元素 集合中只增加了三個物件
*/
coll.add(person1);
coll.add(person2);
coll.add(person3);
//迭代子遍歷
Iterator iter = coll.iterator(); //不需要自已建立迭代器物件,而 是使用方法從集合中獲取
while(iter.hasNext()) { //判斷集合中是否還有下一個元素
Person temp = (Person)iter.next();
System.out.println(temp.getName());
}
System.out.println("----------------------------------");
//將集合轉換為陣列
Object[] persons = coll.toArray(); //只能轉換為Object[]
for(int i = 0; i < persons.length; i++) {
System.out.println(((Person)persons[i]).getName());
}
Person[] persons1 = new Person[coll.size()]; //根據集合大小來構建相同大小的陣列
coll.toArray(persons1); //將集合元素複製到陣列中,這種方式可以使用物件的具體型別
for(int i = 0; i < persons1.length; i++) {
System.out.println(persons1[i].getName());
}
}
public static void main(String[] args) {
TestCollection test = new TestCollection();
test.mutli();
}
}
------------------------------------Set---------------------------------------------------
package com.job.collection.collection_map;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
* Set與list:介面,元素順序,內容(如何判斷Set不允許重複),訪問方式
* Set與Map:介面,存放,內容,關係
*/
public class TestSet {
public static void main(String[] args) {
Set set = new HashSet();
// Set中null值只能加入一個
set.add(null); //null對明只能加入一次
System.out.println(set.size()); //長度為1
set.add(null); //null物件不能重複加入
System.out.println(set.size()); //長度為1
set.clear();
/*
* 絕大多數Java類的例項都可以依次加入到Set中
*/
GeneralClass general1 = new GeneralClass();
set.add(general1);
GeneralClass general2 = new GeneralClass();
set.add(general2);
GeneralClass general3 = new GeneralClass();
set.add(general3);
System.out.println("GeneralClass類個數:" + set.size()); //長度還是為3,表示每個物件都增加了進來。
//通過迭代子迴圈
//Set集合是不能通過下標迴圈的
Iterator iter = set.iterator();
while(iter.hasNext()) {
GeneralClass temp = (GeneralClass)iter.next();
}
set.clear();
/*
* 相同值的String物件也只能加入一次
*/
String str = "Hello";
set.add(str);
System.out.println(set.size()); //長度為1
String str2 = "Hell";
str2 = str2 + "o";
System.out.println(str2);
String str1 = new String("Hello"); //這裡建立兩個新的物件,它和str並不是指向同一個物件,但是他們所致的hashcolde相同
System.out.println("str和str1的地址比較: " + (str == str1)); //false
System.out.println("str和str1的equals比較: " + (str.equals(str1))); //true
System.out.println("str和str3的equals比較: " + (str.equals(str2))); //true
set.add(str1);
set.add(str2);//str1不會增加到集合中
System.out.println(set.size()); //長度還是為1,表示沒有增加
set.clear();
/*
* 實現重寫hashCode和equals方法的類,這將改變類重複規則的計算方法
*/
OverrideClass over1 = new OverrideClass();
set.add(over1);
OverrideClass over2 = new OverrideClass();
set.add(over2);
OverrideClass over3 = new OverrideClass();
set.add(over3);
System.out.println("OverrideClass類個數:" + set.size()); //長度還是為3,表示每個物件都增加了進來。
set.clear();
}
}
/**
* 通常自定義的Java類,一般不會重寫hashCode和equals方法
*/
class GeneralClass {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
/**
* 重寫hashCode和equals方法,改變類的物件相等 的規則
* 實際編 程中一般不會有這個要求
*/
class OverrideClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
* 重寫Object的hashCode方法,提供了自定義的hashCode定義。
* 如果兩個物件的hashCode值不同則認為兩個物件是不相同的,可以按照hashCode值確定物件在Set中的位置
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if(name == null) {
return 1;
}
return name.hashCode();
}
/*
* 重寫Object的equals方法,提供了自定義的equals定義。
* 如果放入Set集合的兩個物件的hashCode值相同,則呼叫equals方法判斷兩個物件是否相等 。
* 如果相等 則不會放入到Set中,如果不等 則放入到Set中。
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
OverrideClass over = (OverrideClass)obj;
if(name == null) {
if(over.getName() == null) {
return true;
} else {
return false;
}
}
return this.name.equals(over.getName());
}
}
--------------------------------------TreeSet-------------------------------------------------
package com.job.collection.collection_map;
import java.util.TreeSet;
import java.util.Iterator;
public class TestTreeSet {
public static void main(String[] args) {
TreeSet<SortClass> set = new TreeSet<SortClass>();
set.add(new SortClass("a"));
set.add(new SortClass("c"));
set.add(new SortClass("b"));
//JDK5中對集合迴圈的新語法
for(SortClass element : set) {
System.out.println(element.getName());
}
//迭代子迴圈,和上面寫法都是遍歷操作
Iterator<SortClass> iter = set.iterator();
while(iter.hasNext()) {
SortClass temp = iter.next();
}
}
}
/**
* TreeSet中只能放入實現Comparable介面的物件
*
* @author Administrator
*
*/
class SortClass implements Comparable {
private String name;
public SortClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public int compareTo(Object obj) {
SortClass sort = (SortClass) obj;
return name.compareTo(sort.getName()); //String類實現了comparable介面
}
}
-------------------------------------HashMap--------------------------------------------------
public static void main(String[] args) {
HashMap map = new HashMap();
//增加
Person person1 = new Person();
person1.setName("王五");
Person person2 = new Person();
person2.setName("張三");
map.put("wang", person1);
map.put("zhang", person2);
//按Key取值
Person person3 = (Person)map.get("zhang");
System.out.println(person3.getName()); //張三
//是否包含某個key值
System.out.println(map.containsKey("wang"));
//替換 使用相同Key賦值時,後面的賦值將替換前面的賦值
map.put("zhang", person1); //使用person1替換原來zhang所對應的值
Person person4 = (Person)map.get("zhang");
System.out.println(person4.getName()); //王五
Person person5 = (Person)map.remove("wang");//按Key刪除值
System.out.println(person5.getName());
System.out.println(map.size()); //大小為1
System.out.println(map.size()); //大小為2
System.out.println(map.isEmpty()); //是否為空
//返回Key集合
map.put("wang", person1);
Set keySet = map.keySet(); //得到Key集合
Iterator iter1 = keySet.iterator();
while(iter1.hasNext()) {
String key = (String)iter1.next(); //得到key值
Person temp = (Person)map.get(key); //返回key對對應的value
System.out.println("key: " + key + " value: " + temp.getName());
}
//返回Value集合
Collection coll = map.values();
Iterator iter2 = coll.iterator();
while(iter2.hasNext()) {
Person temp = (Person)iter2.next(); //得到Value
System.out.println("value: " + temp.getName());
}
//按條目獲取(key、value)
Set entrySet = map.entrySet();
Iterator iter3 = entrySet.iterator();
while(iter3.hasNext()) {
Map.Entry temp = (Map.Entry)iter3.next(); //得到key、Value對
String key = (String)temp.getKey();
Person p = (Person)temp.getValue();
System.out.println("key: " + key + " value: " + p.getName());
}
}
-----------------------------------------Map----------------------------------------------
package com.job.collection.collection_map;
public class StudentScore {
private String project[] = new String[3];
private String name;
private double score[] = new double[3];
public StudentScore(String name ,String project[],double Score[]){
this.name = name;
this.project = project;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printpr(String project[]) {
for(int i = 0;i < project.length;i++){
System.out.print("\t"+project[i]+"\t");
}
}
public void printscore(double[] key) {
for(int i = 0;i <key.length;i++){
System.out.print("\t"+key[i]+"\t");
}
}
public String[] getProject() {
return project;
}
public void setProject(String[] project) {
this.project = project;
}
}
package com.job.collection.collection_map;
/*
* 使用陣列名作為鍵值(如何使用檔名作為鍵值)
* 使用泛型不需要強制轉換
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
public class TestStudet {
public static void main(String[] args) {
String Project[] ={"語文","數學","外語"};
double score1[] = {80 ,90 ,95};
double score2[] = {70 ,92 ,88};
double score3[] = {85 ,89 ,85};
StudentScore stu1 = new StudentScore("張三",Project, score1);
StudentScore stu2 = new StudentScore("李四",Project, score2);
StudentScore stu3 = new StudentScore("王五",Project, score3);
Map<double[],StudentScore> stuscoremap = new HashMap<double[],StudentScore>();
//增加
stuscoremap.put(score1,stu1);
stuscoremap.put(score2,stu2);
stuscoremap.put(score3,stu3);
//是否包含某個key值
System.out.println(stuscoremap .containsKey(score1)); //true
Collection<StudentScore> coll = stuscoremap.values();
Iterator<StudentScore> iter2 = coll.iterator();
Set<double[]> keySet = stuscoremap .keySet(); //得到Key集合
Iterator<double[]> iter1 = keySet.iterator();
System.out.println("姓名: 三科成績");
while(iter2.hasNext()) {
double[] key = iter1.next(); //得到key值
StudentScore temp = (StudentScore )iter2.next(); //得到Value
System.out.println( temp.getName() + "\t");
temp.printpr(Project);
System.out.println( );
temp.printscore(key);
System.out.println( );
}
//返回Key集合
//
//while(iter1.hasNext()) {
//String key = (String)iter1.next(); //得到key值
//StudentScore temp = (StudentScore)stuscore .get(key); //返回key
//}/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
===================================
GeneralClass<T>
===================================
/**
* 定義一個泛型類,使用<T>表示泛型定義
*
* @author Administrator
*
* @param <T>
*/
public class GeneralClass<T> {
private T obj; //T表示由泛型來確定型別
public T getObj() {//T表示由泛型來確定型別
return obj;
}
public void setObj(T obj) {//T表示由泛型來確定型別
this.obj = obj;
}
}
public class Client {
public static void main(String[] args) {
GeneralClass<String> test = new GeneralClass<String>();
test.setObj("test");
String name = test.getObj();
System.out.println(name);
}
}
---------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Apple> box = new ArrayList<Apple>();
Apple apple = new Apple();
box.add(apple); //編譯正確
//Strawberry berry = new Strawberry();
//box.add(berry); //編譯錯誤
Apple apple1 = box.get(0); //不需要顯示造型
HashMap<String, Apple> map = new HashMap<String, Apple>(); //表示key為String型別,Value為Apple型別
map.put("b", new Apple());
Apple apple3 = map.get("b"); //不需要顯示造型
}
}
class Fruit{
}
class Apple extends Fruit {
}
class Strawberry extends Fruit {
}
---------------------------------------------------------------------------------------
========================================
演算法與應用結構
========================================
public class ZhaoQian {
public static void main(String[] args) {
// TODO Auto-generated method stub
double []m = {100,20,10,5,1,0.5,0.1,0.05,0.02,0.01};
Scanner s = new Scanner(System.in);
double money = s.nextDouble();
money(money,m);
}
public static void money(double money,double m[]){
double n[] = new double[m.length];
for(int i=0;i<=n.length-1;i++){
n[0] = Math.floor(money/m[0]);
if(money>0){
n[i] =Math.floor(money/m[i]);
}
money -= n[i]*m[i];
if(n[i]!=0)
System.out.println((int)n[i]+"\t張\t"+m[i]);
}
}
}
---------------------------------------------------------------------------------------
import java.util.Scanner;
public class charu {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[] ={78,9,5,5};
int aa[] = new int [a.length+1];
int h1 = aa.length;
aa[a.length] = n;
for(int i = 0; i <a.length ;i++){
aa[i] = a[i];
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
for(int i=h1-1;i>=1;i--){
if(aa[i]>aa[i-1]){
int temp = aa[i];
aa[i] = aa [i-1];
aa[i-1] = temp;
}
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
for(int i = 0;i<aa.length/2;i++){
int temp = aa[i];
aa[i] = aa[aa.length-1-i];
aa[aa.length-1-i] = temp;
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
// System.out.print(aa[4]+"\t");
for(int i = 0;i<aa.length/2;i++){
aa[i] = aa[i]^aa[aa.length-1-i];
aa[aa.length-1-i] = aa[aa.length-1-i]^aa[i] ;
aa[i] = aa[i]^aa[aa.length-1-i];
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
}
}
==================================================
java Design Patterns
==================================================
/*
建立型模式,共五種:工廠方法模式、抽象工廠模式、單例模式、建造者模式、原型模式。
結構型模式,共七種:介面卡模式、裝飾器模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。
行為型模式,共十一種:策略模式、模板方法模式、觀察者模式、迭代子模式、責任鏈模式、命令模式、
備忘錄模式、狀態模式、訪問者模式、中介者模式、直譯器模式。
1、開閉原則(Open Close Principle)
開閉原則就是說對擴充套件開放,對修改關閉。在程式需要進行拓展的時候,不能去修改原有的程式碼,實現一個熱插拔的效果。
所以一句話概括就是:為了使程式的擴充套件性好,易於維護和升級。想要達到這樣的效果,我們需要使用介面和抽象類,後
面的具體設計中我們會提到這點。
2、里氏代換原則(Liskov Substitution Principle)
里氏代換原則(Liskov Substitution Principle LSP)面向物件設計的基本原則之一。 里氏代換原則中說,
任何基類可以出現的地方,子類一定可以出現。 LSP是繼承複用的基石,只有當衍生類可以替換掉基類,
軟體單位的功能不受到影響時,基類才能真正被複用,而衍生類也能夠在基類的基礎上增加新的行為。
里氏代換原則是對“開-閉”原則的補充。實現“開-閉”原則的關鍵步驟就是抽象化。而基類與子類的繼承關係就是
抽象化的具體實現,所以里氏代換原則是對實現抽象化的具體步驟的規範。
3、依賴倒轉原則(Dependence Inversion Principle)
這個是開閉原則的基礎,具體內容:真對介面程式設計,依賴於抽象而不依賴於具體。
4、介面隔離原則(Interface Segregation Principle)
這個原則的意思是:使用多個隔離的介面,比使用單個介面要好。還是一個降低類之間的耦合度的意思,
從這兒我們看出,其實設計模式就是一個軟體的設計思想,從大型軟體架構出發,為了升級和維護方便。
所以上文中多次出現:降低依賴,降低耦合。
5、迪米特法則(最少知道原則)(Demeter Principle)
為什麼叫最少知道原則,就是說:一個實體應當儘量少的與其他實體之間發生相互作用,使得系統功能模組相對獨立。
6、合成複用原則(Composite Reuse Principle)
原則是儘量使用合成/聚合的方式,而不是使用繼承。*/
---------------------------------------------------------------------------------------
/*
this is Single----------------Single------------------------
*/
class Single{
private static Single s = null;//
private Single(){
}
public static Single getSingle(){
if(s == null) s = new Single();
return s;
}
}
class Single2 {
Single2 s = new Single2();
enum Single{s};
}
---------------------------------------------------------------------------------------
//this is javaCodeConventions
/*
* Classname:MyjavaCodeConventions
*
* Version information:0.0
*
* Date:2014-2-25
*
* Copyright notice
*/
/*
* 命名規範:命名規範使程式更易讀,從而更易於理解。它們也可以提供一些有關識別符號功能的資訊,
* 以助於理解程式碼,例如,不論它是一個常量,包,還是類。
* 程式規範:使易於理解和維護,使效率高,儘量避免無關程式碼
* 包:com.snc.javacode
* 類/介面:MyClass、MyInterface
* 方法:myMethod(),run()
* 變數:短而且易於記憶 int i,j,k ; char c ,d , e;float fvar;
* 例項變數: int _employeeId;String _name;Customer _customer;
* 常量:大寫與下劃線構成 static final int MIN_WIDTH = 4;
* 若沒有足夠理由,不要把例項或類變數宣告為公有。通常,例項變數無需顯式的設定(set)和獲取(gotten),通常這作為方法呼叫的邊緣效應 (side effect)而產生。
* 一個具有公有例項變數的恰當例子,是類僅作為資料結構,沒有行為。亦即,若你要使用一個結構(struct)而非一個類(如果java支援結構的話),
* 那麼把類的例項變數宣告為公有是合適的。
*
*/
package snc;
/**
* to describle the java code conventions
*
* @version 0
* @author Firstname:zjm Lastname:zjm
*
* 文件註釋描述Java的類、介面、構造器,方法,以及欄位(field)
*/
// @註解
/*
* 該註釋應包含任何有關整個類或介面的資訊,而這些資訊又不適合作為類/介面文件註釋。程式編寫:縮排(製表符,if縮排8字元),換行規則(行長度<=70)
* 註釋:文件註釋,實現註釋,註釋不應該包括特殊字元,太多的註釋顯示出程式碼的低質量
*/
/*
* 塊註釋通常用於提供對檔案,方法,資料結構和演算法的描述。 塊註釋被置於每個檔案的開始處以及每個方法之前。它們也可以被用於其他地方,
* 比如方法內部。在功能和方法內部的塊註釋應該和它們所描述的程式碼具有一樣的縮排格式。
*/
/* 如果一個註釋不能在一行內寫完,就該採用塊註釋 */
// 用於註釋多餘的程式碼塊和行尾註釋
public class MyjavaCodeConventions {
/*
* 類的(靜態)變數 首先是類的公共變數,隨後是保護變數,再後是包一級別的變數 (沒有訪問修飾符,access modifier),最後是私有變數。
* 例項變數 首先是公共級別的,隨後是保護級別的,再後是包一級別的(沒有訪問修飾符), 最後是私有級別的。
* 儘量在宣告區域性變數的同時初始化。唯一不這麼做的理由是變數的初始值依賴於某些先前發生的計算只在程式碼塊的開始處宣告變
*/
public static int ivar = 1;
protected boolean bvar = false;
AnotherClass anotherClass = new AnotherClass();
private AnotherClass anoterClass2 = new AnotherClass();
private int b;
/*
* 構造方法
*/
@SuppressWarnings("static-access")
public MyjavaCodeConventions() {
anotherClass = this.anoterClass2;
b = this.ivar;
}
public MyjavaCodeConventions(boolean bvar) {
super();
this.bvar = bvar;
}
/*
* 這些方法應該按功能,而非作用域或訪問許可權,分組。 一個私有的類方法可以置於兩個公有的例項方法之間。其目的是為了更便於閱讀和理解程式碼。
* 斷開程式碼(,後面,操作符前面)
*/
}
class AnotherClass {
}
============================================
test Scanner and Random System
============================================
Random r = new Random();
Scanner s = new Scanner(System.in);
int []a = new int[3];
int []b = new int [10];
for(int i = 0;i < a.length;i++) {
a[i] = s.nextInt();
}
Arrays.sort(a);
int s = (int)n1 + (int)(Math.random()*(n2-n1));
char c = (char)(c1+Math.random()*(c2 - c1 +1));
================================================
some IO util: ------IPO-------
================================================
//各種流之間的巢狀關係
new DataInputStream(new BufferedInputStream(new SequenceInputStream(new FileInputStream("d:\\1"), f1)));
new DataInputStream(new BufferedInputStream(new FileInputStream("d:\\1")));
new DataInputStream(new FileInputStream("d:\\1"));
new ObjectInputStream(new BufferedInputStream(new FileInputStream("d:\\1")));
new ObjectInputStream(new FileInputStream("d:\\1"));
public class IoUtil {
public static void close(InputStream is) {
if (is != null) {
try {
is.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
public static void close(OutputStream os) {
if (os != null) {
try {
os.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
/*讀取檔案+中的檔案,並顯示到面板*/
public static void readFile(String catalog,String fileName){
int b = 0;
byte buffer[] = new byte[2500];
try{
File f = new File(catalog,fileName);
FileInputStream file = new FileInputStream(f);
b = file.read(buffer,0,2500);
try{
String str = new String(buffer,0,b,"Default");
System.out.println(str);
}catch(UnsupportedEncodingException u){
System.out.println("the encoding was not found: "+u);
}
}catch(IOException e){
System.out.println("File is read Error");
}
}
/*複製檔案*/
public static void copyFile(File sorceFile, File targetFile)
throws IOException {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(new FileInputStream(sorceFile));
os = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] b = new byte[1024 * 5];
int len;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
os.flush(); // 關閉連結前需要重新整理緩衝區
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 通過抽取公共方法形成工具類,簡化程式,提高程式碼重用
IoUtil.close(is);
IoUtil.close(os);
}
}
public static void fileReadWritetofile(File inFile,File outFile) throws IOException{
InputStream is = null;
OutputStream os = null;
try{
is = new BufferedInputStream(new FileInputStream(inFile),4*1024);
os = new BufferedOutputStream(new FileOutputStream(outFile),4*1024);
int len = 0;
byte[]bytes = new byte[4*1024];
while((len = is.read(bytes))!= -1){
os.write(bytes,0,len);
}
os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(is);
IoUtil.close(os);
}
}
/* 複製資料夾*/
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目標目錄
(new File(targetDir)).mkdirs();
// 獲取原始檔夾當前下的檔案或目錄
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 原始檔
File sourceFile = file[i];
// 目標檔案
File targetFile = new File(
new File(targetDir).getAbsolutePath() + File.separator
+ file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 準備複製的原始檔夾
String dir1 = sourceDir + "/" + file[i].getName();
// 準備複製的目標資料夾
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
/* the object serializable */
// 持久化物件,將物件寫入到文 件中
public static void writeObject(Object obj, File file) {
// 寫入順序 obj(Object)->oos(ObjectOutStream)--byte[]->fos(FileOutputStream)->file(File)
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(file); // 支援二進位制的文 件寫入流
oos = new ObjectOutputStream(fos); // 將物件流和文
// 件流關聯起來
oos.writeObject(obj);// 將物件轉換為位元組流,並寫入到文 件中
oos.flush();// 將快取中內容刷到介質中
} catch (IOException e) {
e.printStackTrace();
}finally{
// 通過抽取公共方法形成工具類,簡化程式,提高程式碼重用
IoUtil.close(fos);
}
}
// 讀取物件,從文 件中恢復物件
public static Object readObject(File file) {
// 流處理過程 file(File)->fis(FileInputStream)->ois(ObjectInputStram)->object(Object)
Object obj = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(file); //用二進位制流讀取文 件內容
ois = new ObjectInputStream(fis); //將二進位制流提供給物件流解析
obj = ois.readObject(); //根據文 件內容恢復物件
//ois.close();// 關閉文 件流
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 通過抽取公共方法形成工具類,簡化程式,提高程式碼重用
IoUtil.close(ois);
}
return obj;
}
//// 建立序列化物件
//Person person = new Person();
//person.setId(1);
//person.setName("張三");
//person.setPwd("1998998");//pwd 為非序列化元素
//// 物件寫入的文 件 new file ——》寫入--》恢復物件
//File file = new File("c:/object.serperson");
//IoUtil.writeObject(person, file);
//
//// 從序列化文 件中恢復物件
//Person result = (Person)IoUtil.readObject(file);
//System.out.println("id:\t " + result.getId() + " name: "
//+ result.getName() + " \tpwd: \t" + result.getPwd());
////id: 1 name: 張三 pwd: null
public static void printDataoutputstreamTofile(String s,File f)throws IOException{
DataOutputStream ds = null;
try{
ds = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
ds.writeUTF(s);
ds.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(ds);
}
}
public static void printWriter(String s,File f)throws IOException{
PrintWriter p = null;
try{
p = new PrintWriter(f);
p.println(s);
}catch(IOException e){
e.printStackTrace();
}finally{
if (p != null) {
p.close();// 關閉文 件流
}
}
}
public static void testWriter(char[]chars, File f)throws Exception{
FileWriter w = null;
try{
w = new FileWriter(f);
w.write(chars);
w.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
if (w != null) {
try {
w.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
}
public static void fileReadWritetofile(File inFile,File outFile) throws IOException{
InputStream is = null;
OutputStream os = null;
try{
is = new BufferedInputStream(new FileInputStream(inFile),4*1024);
os = new BufferedOutputStream(new FileOutputStream(outFile),4*1024);
int len = 0;
byte[]bytes = new byte[4*1024];
while((len = is.read(bytes))!= -1){
os.write(bytes,0,len);
}
os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(is);
IoUtil.close(os);
}
}
public static void writeGBK(){
OutputStreamWriter osw = null;
try{
osw = new OutputStreamWriter( new FileOutputStream("c:\\gbk.txt"),"GBK");
osw.write("abc");
osw.write("釋出");
osw.flush();
}catch(IOException e){
System.out.println(e);
}finally{
if (osw != null) {
try {
osw.close();// 關閉文 件流
} catch (IOException e) {
// 由於本錯添沒有處理價值,因此在異常處理程式碼中不做任何處理
// 最多在日 志中記錄一下當前文 件無法關閉
}
}
}
}
public static void readGBK(){
try{
BufferedReader reader
= new BufferedReader(new InputStreamReader(new FileInputStream("C:\\gbk.txt"),"GBK"));
String s;
while((s = reader.readLine())!=null){
System.out.println("read: "+s);
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void readUTF8(){
try{
BufferedReader reader
= new BufferedReader(new InputStreamReader(new FileInputStream("c:\\gbk.txt"),"UTF-8"));
String s;
while((s = reader.readLine())!=null){
System.out.println("read: "+s);
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
================================================
Exception
================================================
try
{
是必須的
}
catch ()
{
可有多個
}
finally 程式碼必須得到執行,try與finally最多一個
java.lang.Object
|
-|----.Throwable
-|----.Error
-|----.Exception
-|----.IOException
-|----.RuntimeException
-|----.ArithmeticException
-|----.ArrayIndexOutOfBoundsException
-|----.NumberFormatException
//Account //存錢//取款throws InsufficientFundsException(自定義異常)
public class Account {
private String name; //取款人姓名
private double balance; //餘額
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
//存錢
public void deposite(double dAmount) {
if(dAmount > 0.0) balance += dAmount;
}
//取款
public void withdrawal(double dAmount) throws InsufficientFundsException {
if(dAmount > balance) {
String message = "取款金額超過了賬戶的當前餘額";
throw new InsufficientFundsException(message, this, dAmount);
}
balance = balance - dAmount;
}
}
/**
* 首先自定義異常 類
* @author Administrator
*
*/
public class InsufficientFundsException extends Exception {
private Account account; //賬號
private double excepAmount; //異常 的取款金額
//message引數是傳給Exception類的
public InsufficientFundsException(String message, Account account, double dAmount) {
super(message);
this.account = account;
this.excepAmount = dAmount;
}
public Account getAccount() {
return account;
}
public double getExcepAmount() {
return excepAmount;
}
}
//Client
public class Client {
public static void main(String[] args) {
//初始化一個賬號
Account account = new Account("張三", 1000.0);
//存錢
account.deposite(100);
//查詢餘額
System.out.println("當前餘額是: " + account.getBalance());
//取款(處理業務的try)
try{
account.withdrawal(50);
} catch(InsufficientFundsException e) {
e.printStackTrace(); //這是簡單的異常 處理方式,直接將錯誤資訊輸出到控制檯。實際專案中會使用log4j將鉕誤資訊記錄到日 志中,以便以後進行統計分析
}
//查詢餘額
System.out.println("取款50後的當前餘額是: " + account.getBalance());
try{
account.withdrawal(10000);
} catch(InsufficientFundsException e) {
e.printStackTrace(); //這是簡單的異常 處理方式,直接將錯誤資訊輸出到控制檯。實際專案中會使用log4j將鉕誤資訊記錄到日 志中,以便以後進行統計分析
}
}
}
static int test(){
int x = 1;
try{
return x;
}
finally{
++x;
System.out.print("x=");
//return x; //無返回1,有返回2
}
}
==================================================
java集合框架(對外的介面,介面的實現,集合的演算法) Collection Map
==================================================
interface.java.util.Collection
|
-|----.List
-|----.Set
-|----.SortedSet
interface.java.util.Map
|
-|----.SortedMap
------------------------------------------List:ArrayList---------------------------------------------
System.out.println("這是ArrayListd的例子:add(),get(),set(),remove(),和兩種遍歷方式:");
String str[] = {"ab","cd","er","gh","ij"};
ArrayList list = new ArrayList();
list.add("litter are: ");
for(int i = 0;i < str.length; i++){
list.add(str[i]);
}
list.add(",that's all");
System.out.println("the arraylist is: ");
for(int i = 0;i < list.size();i++){
System.out.print(list.get(i));
}
System.out.println();
//list.remove(1);
list.set(4,"AB");//設定陣列第4個為AB
Iterator iter = list.iterator();
while(iter.hasNext()){
Object temp = iter.next();
System.out.print(temp);
}
System.out.println();
}
---------------------------------------------------------------------------------------
public static void main(String[] args) {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
list.add("g");
Iterator iter = list.iterator();
while(iter.hasNext()) {
String node = (String)iter.next();
System.out.println(node);
iter.remove();
//遍歷集合時不要刪除集合中的元素,這樣通常 會引發異常
//list.remove(6);
}
}
---------------------------------------------------------------------------------------
public static void main(String[] args) {
List list = new ArrayList();
//基本操作
Person person = new Person();
person.setName("person");
list.add(person);
System.out.println(list.size());
System.out.println(list.isEmpty());
/*
* 與索引下載有關的方法
*/
Person person1 = new Person();
person1.setName("person1");
list.add(0, person1); //將person1插入到集合的第一個位置
Person person2 = new Person();
person2.setName("person2");
list.set(0, person2); //將person2替換到集合的第一個位置
System.out.println(list.indexOf(person2)); //確定person2的下標
/*
* 支援下標索引迴圈和迭代子迴圈
*/
//遍歷 類似於陣列使用下標遍歷,下標從0開始
for(int i = 0; i < list.size(); i++) {
Person temp = (Person)list.get(i);
System.out.println(temp.getName());
}
//迭代子迴圈 這是另一種對集合遍歷的方式
Iterator iter = list.iterator();
while(iter.hasNext()) {
Person temp = (Person)iter.next();
System.out.println(temp.getName());
}
}
---------------------------------------LinkedList------------------------------------------------
package com.job.collection.collection_map;
/*
* Collection
* |_ _ _Set
* | |_ _SortedSet
* | | |__TreeSet
* | |__HashSet
* |
* |_ _ _List
* |___ArrayList
* |___LinkedList
* 對集合框架的理解,各個結合間的區別,使用
*/
public static void main(String[] args) {
//棧實現 先進後出、後進先出
LinkedList stack = new LinkedList();
stack.push("a"); //入棧
stack.push("b");
System.out.println(stack.size()); //棧大小
String temp = (String)stack.pop(); //出棧
System.out.println("temp: " + temp); //b
//佇列實現 先進先出
LinkedList queue = new LinkedList();
queue.addLast("a"); //入佇列
queue.addLast("b");
queue.addLast("c");
System.out.println(queue.size()); //佇列大小
while(queue.isEmpty()){
String temp1 = (String)queue.poll(); //出佇列
System.out.println("temp1: " + temp1); //a
}
}
-------------------------Collection----------------------------
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class TestCollection {
//單 個集合元素的操作
public void single() {
Collection coll = new ArrayList();
Person person = new Person();
System.out.println(coll.add(person)); //增加第一個元素,返回true
System.out.println(coll.size()); //此時集合大小為1
System.out.println(coll.isEmpty()); //判斷集合是否為空
System.out.println(coll.contains(person)); //判斷集合是否包含指定物件
System.out.println("----------------------------------");
System.out.println(coll.remove(person)); //刪除元素,返回true
System.out.println(coll.size()); //此時集合大小為0
System.out.println(coll.isEmpty()); //判斷集合是否為空
System.out.println(coll.contains(person)); //判斷集合是否包含指定物件
}
//多個集合地素的操作
public void mutli() {
//構造集合物件
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
Person person3 = new Person();
person3.setName("person3");
Person person4 = new Person();
person4.setName("person4");
Person person5 = new Person();
person5.setName("person5");
Person person6 = new Person();
person6.setName("person6");
String str = "Hello";
//構造第一個集合
Collection coll = new ArrayList();
coll.add(person1);
coll.add(person2);
coll.add(person3);
//構造第二個集合
Collection coll2 = new ArrayList();
coll2.add(person4);
coll2.add(person5);
coll2.add(person6);
coll2.add(str);
/*
* 集合間操作
*/
coll.addAll(coll2); //將第二個集合加入到第一個集合中
System.out.println(coll.size()); //此時集合大小為7
System.out.println(coll.containsAll(coll2)); //判斷集合是否包含指定集合中的所有物件
System.out.println("----------------------------------");
coll.removeAll(coll2); //刪除指定集合中的所有物件
System.out.println(coll.size()); //此時集合大小為3
coll.retainAll(coll2); //刪除coll中所有不被coll2包含的集合元素
System.out.println(coll.size()); //此時集合大小為0
coll.add(person1);
coll.add(person2);
coll.add(person3);
coll.clear();
System.out.println(coll.size()); //此時集合大小為0
System.out.println("----------------------------------");
/*
* 遍歷集合元素 集合中只增加了三個物件
*/
coll.add(person1);
coll.add(person2);
coll.add(person3);
//迭代子遍歷
Iterator iter = coll.iterator(); //不需要自已建立迭代器物件,而 是使用方法從集合中獲取
while(iter.hasNext()) { //判斷集合中是否還有下一個元素
Person temp = (Person)iter.next();
System.out.println(temp.getName());
}
System.out.println("----------------------------------");
//將集合轉換為陣列
Object[] persons = coll.toArray(); //只能轉換為Object[]
for(int i = 0; i < persons.length; i++) {
System.out.println(((Person)persons[i]).getName());
}
Person[] persons1 = new Person[coll.size()]; //根據集合大小來構建相同大小的陣列
coll.toArray(persons1); //將集合元素複製到陣列中,這種方式可以使用物件的具體型別
for(int i = 0; i < persons1.length; i++) {
System.out.println(persons1[i].getName());
}
}
public static void main(String[] args) {
TestCollection test = new TestCollection();
test.mutli();
}
}
------------------------------------Set---------------------------------------------------
package com.job.collection.collection_map;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
* Set與list:介面,元素順序,內容(如何判斷Set不允許重複),訪問方式
* Set與Map:介面,存放,內容,關係
*/
public class TestSet {
public static void main(String[] args) {
Set set = new HashSet();
// Set中null值只能加入一個
set.add(null); //null對明只能加入一次
System.out.println(set.size()); //長度為1
set.add(null); //null物件不能重複加入
System.out.println(set.size()); //長度為1
set.clear();
/*
* 絕大多數Java類的例項都可以依次加入到Set中
*/
GeneralClass general1 = new GeneralClass();
set.add(general1);
GeneralClass general2 = new GeneralClass();
set.add(general2);
GeneralClass general3 = new GeneralClass();
set.add(general3);
System.out.println("GeneralClass類個數:" + set.size()); //長度還是為3,表示每個物件都增加了進來。
//通過迭代子迴圈
//Set集合是不能通過下標迴圈的
Iterator iter = set.iterator();
while(iter.hasNext()) {
GeneralClass temp = (GeneralClass)iter.next();
}
set.clear();
/*
* 相同值的String物件也只能加入一次
*/
String str = "Hello";
set.add(str);
System.out.println(set.size()); //長度為1
String str2 = "Hell";
str2 = str2 + "o";
System.out.println(str2);
String str1 = new String("Hello"); //這裡建立兩個新的物件,它和str並不是指向同一個物件,但是他們所致的hashcolde相同
System.out.println("str和str1的地址比較: " + (str == str1)); //false
System.out.println("str和str1的equals比較: " + (str.equals(str1))); //true
System.out.println("str和str3的equals比較: " + (str.equals(str2))); //true
set.add(str1);
set.add(str2);//str1不會增加到集合中
System.out.println(set.size()); //長度還是為1,表示沒有增加
set.clear();
/*
* 實現重寫hashCode和equals方法的類,這將改變類重複規則的計算方法
*/
OverrideClass over1 = new OverrideClass();
set.add(over1);
OverrideClass over2 = new OverrideClass();
set.add(over2);
OverrideClass over3 = new OverrideClass();
set.add(over3);
System.out.println("OverrideClass類個數:" + set.size()); //長度還是為3,表示每個物件都增加了進來。
set.clear();
}
}
/**
* 通常自定義的Java類,一般不會重寫hashCode和equals方法
*/
class GeneralClass {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
/**
* 重寫hashCode和equals方法,改變類的物件相等 的規則
* 實際編 程中一般不會有這個要求
*/
class OverrideClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
* 重寫Object的hashCode方法,提供了自定義的hashCode定義。
* 如果兩個物件的hashCode值不同則認為兩個物件是不相同的,可以按照hashCode值確定物件在Set中的位置
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if(name == null) {
return 1;
}
return name.hashCode();
}
/*
* 重寫Object的equals方法,提供了自定義的equals定義。
* 如果放入Set集合的兩個物件的hashCode值相同,則呼叫equals方法判斷兩個物件是否相等 。
* 如果相等 則不會放入到Set中,如果不等 則放入到Set中。
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
OverrideClass over = (OverrideClass)obj;
if(name == null) {
if(over.getName() == null) {
return true;
} else {
return false;
}
}
return this.name.equals(over.getName());
}
}
--------------------------------------TreeSet-------------------------------------------------
package com.job.collection.collection_map;
import java.util.TreeSet;
import java.util.Iterator;
public class TestTreeSet {
public static void main(String[] args) {
TreeSet<SortClass> set = new TreeSet<SortClass>();
set.add(new SortClass("a"));
set.add(new SortClass("c"));
set.add(new SortClass("b"));
//JDK5中對集合迴圈的新語法
for(SortClass element : set) {
System.out.println(element.getName());
}
//迭代子迴圈,和上面寫法都是遍歷操作
Iterator<SortClass> iter = set.iterator();
while(iter.hasNext()) {
SortClass temp = iter.next();
}
}
}
/**
* TreeSet中只能放入實現Comparable介面的物件
*
* @author Administrator
*
*/
class SortClass implements Comparable {
private String name;
public SortClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public int compareTo(Object obj) {
SortClass sort = (SortClass) obj;
return name.compareTo(sort.getName()); //String類實現了comparable介面
}
}
-------------------------------------HashMap--------------------------------------------------
public static void main(String[] args) {
HashMap map = new HashMap();
//增加
Person person1 = new Person();
person1.setName("王五");
Person person2 = new Person();
person2.setName("張三");
map.put("wang", person1);
map.put("zhang", person2);
//按Key取值
Person person3 = (Person)map.get("zhang");
System.out.println(person3.getName()); //張三
//是否包含某個key值
System.out.println(map.containsKey("wang"));
//替換 使用相同Key賦值時,後面的賦值將替換前面的賦值
map.put("zhang", person1); //使用person1替換原來zhang所對應的值
Person person4 = (Person)map.get("zhang");
System.out.println(person4.getName()); //王五
Person person5 = (Person)map.remove("wang");//按Key刪除值
System.out.println(person5.getName());
System.out.println(map.size()); //大小為1
System.out.println(map.size()); //大小為2
System.out.println(map.isEmpty()); //是否為空
//返回Key集合
map.put("wang", person1);
Set keySet = map.keySet(); //得到Key集合
Iterator iter1 = keySet.iterator();
while(iter1.hasNext()) {
String key = (String)iter1.next(); //得到key值
Person temp = (Person)map.get(key); //返回key對對應的value
System.out.println("key: " + key + " value: " + temp.getName());
}
//返回Value集合
Collection coll = map.values();
Iterator iter2 = coll.iterator();
while(iter2.hasNext()) {
Person temp = (Person)iter2.next(); //得到Value
System.out.println("value: " + temp.getName());
}
//按條目獲取(key、value)
Set entrySet = map.entrySet();
Iterator iter3 = entrySet.iterator();
while(iter3.hasNext()) {
Map.Entry temp = (Map.Entry)iter3.next(); //得到key、Value對
String key = (String)temp.getKey();
Person p = (Person)temp.getValue();
System.out.println("key: " + key + " value: " + p.getName());
}
}
-----------------------------------------Map----------------------------------------------
package com.job.collection.collection_map;
public class StudentScore {
private String project[] = new String[3];
private String name;
private double score[] = new double[3];
public StudentScore(String name ,String project[],double Score[]){
this.name = name;
this.project = project;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printpr(String project[]) {
for(int i = 0;i < project.length;i++){
System.out.print("\t"+project[i]+"\t");
}
}
public void printscore(double[] key) {
for(int i = 0;i <key.length;i++){
System.out.print("\t"+key[i]+"\t");
}
}
public String[] getProject() {
return project;
}
public void setProject(String[] project) {
this.project = project;
}
}
package com.job.collection.collection_map;
/*
* 使用陣列名作為鍵值(如何使用檔名作為鍵值)
* 使用泛型不需要強制轉換
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
public class TestStudet {
public static void main(String[] args) {
String Project[] ={"語文","數學","外語"};
double score1[] = {80 ,90 ,95};
double score2[] = {70 ,92 ,88};
double score3[] = {85 ,89 ,85};
StudentScore stu1 = new StudentScore("張三",Project, score1);
StudentScore stu2 = new StudentScore("李四",Project, score2);
StudentScore stu3 = new StudentScore("王五",Project, score3);
Map<double[],StudentScore> stuscoremap = new HashMap<double[],StudentScore>();
//增加
stuscoremap.put(score1,stu1);
stuscoremap.put(score2,stu2);
stuscoremap.put(score3,stu3);
//是否包含某個key值
System.out.println(stuscoremap .containsKey(score1)); //true
Collection<StudentScore> coll = stuscoremap.values();
Iterator<StudentScore> iter2 = coll.iterator();
Set<double[]> keySet = stuscoremap .keySet(); //得到Key集合
Iterator<double[]> iter1 = keySet.iterator();
System.out.println("姓名: 三科成績");
while(iter2.hasNext()) {
double[] key = iter1.next(); //得到key值
StudentScore temp = (StudentScore )iter2.next(); //得到Value
System.out.println( temp.getName() + "\t");
temp.printpr(Project);
System.out.println( );
temp.printscore(key);
System.out.println( );
}
//返回Key集合
//
//while(iter1.hasNext()) {
//String key = (String)iter1.next(); //得到key值
//StudentScore temp = (StudentScore)stuscore .get(key); //返回key
//}/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
===================================
GeneralClass<T>
===================================
/**
* 定義一個泛型類,使用<T>表示泛型定義
*
* @author Administrator
*
* @param <T>
*/
public class GeneralClass<T> {
private T obj; //T表示由泛型來確定型別
public T getObj() {//T表示由泛型來確定型別
return obj;
}
public void setObj(T obj) {//T表示由泛型來確定型別
this.obj = obj;
}
}
public class Client {
public static void main(String[] args) {
GeneralClass<String> test = new GeneralClass<String>();
test.setObj("test");
String name = test.getObj();
System.out.println(name);
}
}
---------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Apple> box = new ArrayList<Apple>();
Apple apple = new Apple();
box.add(apple); //編譯正確
//Strawberry berry = new Strawberry();
//box.add(berry); //編譯錯誤
Apple apple1 = box.get(0); //不需要顯示造型
HashMap<String, Apple> map = new HashMap<String, Apple>(); //表示key為String型別,Value為Apple型別
map.put("b", new Apple());
Apple apple3 = map.get("b"); //不需要顯示造型
}
}
class Fruit{
}
class Apple extends Fruit {
}
class Strawberry extends Fruit {
}
---------------------------------------------------------------------------------------
========================================
演算法與應用結構
========================================
public class ZhaoQian {
public static void main(String[] args) {
// TODO Auto-generated method stub
double []m = {100,20,10,5,1,0.5,0.1,0.05,0.02,0.01};
Scanner s = new Scanner(System.in);
double money = s.nextDouble();
money(money,m);
}
public static void money(double money,double m[]){
double n[] = new double[m.length];
for(int i=0;i<=n.length-1;i++){
n[0] = Math.floor(money/m[0]);
if(money>0){
n[i] =Math.floor(money/m[i]);
}
money -= n[i]*m[i];
if(n[i]!=0)
System.out.println((int)n[i]+"\t張\t"+m[i]);
}
}
}
---------------------------------------------------------------------------------------
import java.util.Scanner;
public class charu {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[] ={78,9,5,5};
int aa[] = new int [a.length+1];
int h1 = aa.length;
aa[a.length] = n;
for(int i = 0; i <a.length ;i++){
aa[i] = a[i];
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
for(int i=h1-1;i>=1;i--){
if(aa[i]>aa[i-1]){
int temp = aa[i];
aa[i] = aa [i-1];
aa[i-1] = temp;
}
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
for(int i = 0;i<aa.length/2;i++){
int temp = aa[i];
aa[i] = aa[aa.length-1-i];
aa[aa.length-1-i] = temp;
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
// System.out.print(aa[4]+"\t");
for(int i = 0;i<aa.length/2;i++){
aa[i] = aa[i]^aa[aa.length-1-i];
aa[aa.length-1-i] = aa[aa.length-1-i]^aa[i] ;
aa[i] = aa[i]^aa[aa.length-1-i];
}
for(int val:aa)
System.out.print(val+"\t");
System.out.println();
}
}
==================================================
java Design Patterns
==================================================
/*
建立型模式,共五種:工廠方法模式、抽象工廠模式、單例模式、建造者模式、原型模式。
結構型模式,共七種:介面卡模式、裝飾器模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。
行為型模式,共十一種:策略模式、模板方法模式、觀察者模式、迭代子模式、責任鏈模式、命令模式、
備忘錄模式、狀態模式、訪問者模式、中介者模式、直譯器模式。
1、開閉原則(Open Close Principle)
開閉原則就是說對擴充套件開放,對修改關閉。在程式需要進行拓展的時候,不能去修改原有的程式碼,實現一個熱插拔的效果。
所以一句話概括就是:為了使程式的擴充套件性好,易於維護和升級。想要達到這樣的效果,我們需要使用介面和抽象類,後
面的具體設計中我們會提到這點。
2、里氏代換原則(Liskov Substitution Principle)
里氏代換原則(Liskov Substitution Principle LSP)面向物件設計的基本原則之一。 里氏代換原則中說,
任何基類可以出現的地方,子類一定可以出現。 LSP是繼承複用的基石,只有當衍生類可以替換掉基類,
軟體單位的功能不受到影響時,基類才能真正被複用,而衍生類也能夠在基類的基礎上增加新的行為。
里氏代換原則是對“開-閉”原則的補充。實現“開-閉”原則的關鍵步驟就是抽象化。而基類與子類的繼承關係就是
抽象化的具體實現,所以里氏代換原則是對實現抽象化的具體步驟的規範。
3、依賴倒轉原則(Dependence Inversion Principle)
這個是開閉原則的基礎,具體內容:真對介面程式設計,依賴於抽象而不依賴於具體。
4、介面隔離原則(Interface Segregation Principle)
這個原則的意思是:使用多個隔離的介面,比使用單個介面要好。還是一個降低類之間的耦合度的意思,
從這兒我們看出,其實設計模式就是一個軟體的設計思想,從大型軟體架構出發,為了升級和維護方便。
所以上文中多次出現:降低依賴,降低耦合。
5、迪米特法則(最少知道原則)(Demeter Principle)
為什麼叫最少知道原則,就是說:一個實體應當儘量少的與其他實體之間發生相互作用,使得系統功能模組相對獨立。
6、合成複用原則(Composite Reuse Principle)
原則是儘量使用合成/聚合的方式,而不是使用繼承。*/
---------------------------------------------------------------------------------------