日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

java 8入门与实践_30个Java入门技巧和最佳实践

發(fā)布時(shí)間:2023/12/3 java 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 8入门与实践_30个Java入门技巧和最佳实践 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

java 8入門與實(shí)踐

Java是最流行的編程語言之一-無論是Win應(yīng)用程序,Web應(yīng)用程序,移動,網(wǎng)絡(luò),消費(fèi)電子產(chǎn)品,機(jī)頂盒設(shè)備,Java隨處可見。

在Java上運(yùn)行的設(shè)備超過30億。 據(jù)Oracle稱 ,正在使用50億張Java卡。

超過900萬開發(fā)人員選擇用Java編寫代碼,該代碼在開發(fā)人員中非常流行,同時(shí)也是最流行的開發(fā)平臺。

對于即將到來的Java開發(fā)人員,此博客提供了一段時(shí)間內(nèi)已學(xué)習(xí)的最佳實(shí)踐的集合:

1.最好返回空集合而不是空

如果程序返回的集合沒有任何值,請確保返回Empty集合而不是Null元素。 這樣可以節(jié)省大量對Null Elements進(jìn)行的“ if else ”測試。

public class getLocationName {return (null==cityName ? "": cityName); }

2.小??心使用琴弦

如果在“ for”循環(huán)中使用“ +”運(yùn)算符連接了兩個(gè)字符串,則每次都會創(chuàng)建一個(gè)新的字符串對象。 這會導(dǎo)致內(nèi)存浪費(fèi)并增加性能時(shí)間。 另外,在實(shí)例化String對象時(shí),應(yīng)避免構(gòu)造函數(shù),而應(yīng)直接進(jìn)行實(shí)例化。 例如:

//Slower Instantiation String bad = new String("Yet another string object");//Faster Instantiation String good = "Yet another string object"

3.避免不必要的物體

對象創(chuàng)建是Java中最昂貴的操作(就內(nèi)存利用率而言)。 因此,建議僅在必要時(shí)才創(chuàng)建或初始化對象。 以下代碼給出了一個(gè)示例:

import java.util.ArrayList; import java.util.List;public class Employees {private List Employees;public List getEmployees() {//initialize only when requiredif(null == Employees) {Employees = new ArrayList();}return Employees;} }

4. Array和ArrayList之間的困境

開發(fā)人員經(jīng)常發(fā)現(xiàn)很難決定是否應(yīng)該使用ArrayList類型的Array類型數(shù)據(jù)結(jié)構(gòu)。 他們都有自己的優(yōu)點(diǎn)和缺點(diǎn)。 選擇實(shí)際上取決于要求。

import java.util.ArrayList;public class arrayVsArrayList {public static void main(String[] args) {int[] myArray = new int[6];myArray[7]= 10; // ArraysOutOfBoundException//Declaration of ArrayList. Add and Remove of elements is easy.ArrayList<Integer> myArrayList = new ArrayList<>();myArrayList.add(1);myArrayList.add(2);myArrayList.add(3);myArrayList.add(4);myArrayList.add(5);myArrayList.remove(0);for(int i = 0; i < myArrayList.size(); i++) {System.out.println("Element: " + myArrayList.get(i));}//Multi-dimensional Array int[][][] multiArray = new int [3][3][3]; } }
  • 數(shù)組的大小固定,但ArrayList的大小可變。 由于Array的大小是固定的,因此在聲明Array類型變量時(shí)會分配內(nèi)存。 因此,數(shù)組非常快。 另一方面,如果我們不知道數(shù)據(jù)的大小,那么ArrayList為:更多數(shù)據(jù)將導(dǎo)致ArrayOutOfBoundException,而較少數(shù)據(jù)將導(dǎo)致存儲空間的浪費(fèi)。
  • 從ArrayList添加或刪除元素比Array要容易得多
  • 數(shù)組可以是多維的,但ArrayList只能是一維的。
  • 5.最終無法通過Try執(zhí)行時(shí)

    考慮以下代碼段:

    public class shutDownHooksDemo {public static void main(String[] args) {for(int i=0;i<5;i++){try {if(i==4) {System.out.println("Inside Try Block.Exiting without executing Finally block.");System.exit(0);}}finally {System.out.println("Inside Finally Block.");}}} }

    在程序中, finally塊中的“ println”看起來將執(zhí)行5次。 但是,如果執(zhí)行該程序,則用戶會發(fā)現(xiàn), finally塊僅被調(diào)用了4次。 在第五次迭代中, 退出函數(shù)將被調(diào)用, 最后再也不會被第五次調(diào)用。 原因是-System.exit暫停所有正在運(yùn)行的線程(包括當(dāng)前線程)的執(zhí)行。 在嘗試執(zhí)行退出后,即使finally塊也無法執(zhí)行。

    調(diào)用System.exit時(shí) ,JVM在關(guān)閉之前執(zhí)行兩項(xiàng)清理任務(wù):

    首先,它執(zhí)行所有已向Runtime.addShutdownHook注冊的關(guān)機(jī)鉤子 。 這非常有用,因?yàn)樗尫帕薐VM外部的資源。

    其次是與終結(jié)器有關(guān)。 System.runFinalizersOnExit或Runtime.runFinalizersOnExit 。 終結(jié)器的使用從很久以前就已被棄用。 終結(jié)器可以在由其他線程操縱的活動對象上運(yùn)行,這會導(dǎo)致不良結(jié)果甚至死鎖。

    public class shutDownHooksDemo {public static void main(String[] args) {for(int i=0;i<5;i++){final int final_i = i;try {Runtime.getRuntime().addShutdownHook(new Thread() {public void run() {if(final_i==4) {System.out.println("Inside Try Block.Exiting without executing Finally block.");System.exit(0);}}});}finally {System.out.println("Inside Finally Block.");}}} }

    6.檢查可能性

    看看下面的代碼行,確定它們是否可以用來精確識別給定的數(shù)字是否為奇數(shù)?

    public boolean oddOrNot(int num) {return num % 2 == 1; }

    這些行看似正確,但是每四次將返回一次錯(cuò)誤的結(jié)果(從統(tǒng)計(jì)意義上來說)。 考慮一個(gè)負(fù)的奇數(shù),除以2的余數(shù)將不是1。因此,返回的結(jié)果將為false,這是不正確的!

    可以固定如下:

    public boolean oddOrNot(int num) {return (num & 1) != 0; }

    使用此代碼,不僅可以解決負(fù)奇數(shù)的問題,而且可以對代碼進(jìn)行高度優(yōu)化。 由于算術(shù)和邏輯運(yùn)算與除法和乘法相比要快得多,因此在第二個(gè)代碼段中,可以更快地獲得結(jié)果。

    7.單引號和雙引號之間的區(qū)別

    public class Haha {public static void main(String args[]) {System.out.print("H" + "a");System.out.print('H' + 'a');} }

    從代碼看,似乎返回了“ HaHa”,但實(shí)際上返回了Ha169。 原因是,如果使用雙引號,則將字符視為字符串,但如果使用單引號,則將char值的操作數(shù)(“ H”和“ a”)通過稱為加寬基元轉(zhuǎn)換的過程轉(zhuǎn)換為int值。 整數(shù)轉(zhuǎn)換后,將數(shù)字相加并返回169。

    8.通過簡單的技巧避免內(nèi)存泄漏

    內(nèi)存泄漏通常會導(dǎo)致軟件性能下降。 由于Java自動管理內(nèi)存,因此開發(fā)人員沒有太多控制權(quán)。 但是仍然有一些標(biāo)準(zhǔn)做法可以用來防止內(nèi)存泄漏。

    • 查詢完成后,請始終釋放數(shù)據(jù)庫連接。
    • 嘗試盡可能經(jīng)常使用Final塊。
    • 釋放存儲在靜態(tài)表中的實(shí)例。

    9.避免Java中的死鎖

    死鎖的發(fā)生可能有多種原因。 沒有避免死鎖的單一方法。 通常,當(dāng)一個(gè)同步對象正在等待另一同步對象鎖定的資源上的鎖時(shí),就會發(fā)生死鎖。

    嘗試運(yùn)行以下程序。 該程序演示了死鎖。 之所以會出現(xiàn)此死鎖,是因?yàn)閮蓚€(gè)線程都在等待其他線程獲取的資源。 他們倆都在等待,沒有人釋放。

    public class DeadlockDemo {public static Object addLock = new Object();public static Object subLock = new Object();public static void main(String args[]) {MyAdditionThread add = new MyAdditionThread();MySubtractionThread sub = new MySubtractionThread();add.start();sub.start();} private static class MyAdditionThread extends Thread {public void run() {synchronized (addLock) {int a = 10, b = 3;int c = a + b;System.out.println("Addition Thread: " + c);System.out.println("Holding First Lock...");try { Thread.sleep(10); }catch (InterruptedException e) {}System.out.println("Addition Thread: Waiting for AddLock...");synchronized (subLock) {System.out.println("Threads: Holding Add and Sub Locks...");}}}}private static class MySubtractionThread extends Thread {public void run() {synchronized (subLock) {int a = 10, b = 3;int c = a - b;System.out.println("Subtraction Thread: " + c);System.out.println("Holding Second Lock...");try { Thread.sleep(10); }catch (InterruptedException e) {}System.out.println("Subtraction Thread: Waiting for SubLock...");synchronized (addLock) {System.out.println("Threads: Holding Add and Sub Locks...");}}}} }

    輸出:

    ===== Addition Thread: 13 Subtraction Thread: 7 Holding First Lock... Holding Second Lock... Addition Thread: Waiting for AddLock... Subtraction Thread: Waiting for SubLock...

    但是,如果更改了調(diào)用線程的順序,則可以解決死鎖問題。

    public class DeadlockSolutionDemo {public static Object addLock = new Object();public static Object subLock = new Object();public static void main(String args[]) {MyAdditionThread add = new MyAdditionThread();MySubtractionThread sub = new MySubtractionThread();add.start();sub.start();}private static class MyAdditionThread extends Thread {public void run() {synchronized (addLock) {int a = 10, b = 3;int c = a + b;System.out.println("Addition Thread: " + c);System.out.println("Holding First Lock...");try { Thread.sleep(10); }catch (InterruptedException e) {}System.out.println("Addition Thread: Waiting for AddLock...");synchronized (subLock) {System.out.println("Threads: Holding Add and Sub Locks...");}}}}private static class MySubtractionThread extends Thread {public void run() {synchronized (addLock) {int a = 10, b = 3;int c = a - b;System.out.println("Subtraction Thread: " + c);System.out.println("Holding Second Lock...");try { Thread.sleep(10); }catch (InterruptedException e) {}System.out.println("Subtraction Thread: Waiting for SubLock...");synchronized (subLock) {System.out.println("Threads: Holding Add and Sub Locks...");}}}} }

    輸出:

    ===== Addition Thread: 13 Holding First Lock... Addition Thread: Waiting for AddLock... Threads: Holding Add and Sub Locks... Subtraction Thread: 7 Holding Second Lock... Subtraction Thread: Waiting for SubLock... Threads: Holding Add and Sub Locks...

    10.為Java保留內(nèi)存

    一些Java應(yīng)用程序可能會占用大量CPU,并且需要大量RAM。 由于較高的RAM需求,此類應(yīng)用程序通常運(yùn)行緩慢。 為了提高此類應(yīng)用程序的性能,RAM保留用于Java。 因此,例如,如果我們有一個(gè)Tomcat Web服務(wù)器,并且它具有10 GB的RAM。 如果愿意,可以使用以下命令在此計(jì)算機(jī)上為Java分配RAM:

    export JAVA_OPTS="$JAVA_OPTS -Xms5000m -Xmx6000m -XX:PermSize=1024m -XX:MaxPermSize=2048m"
    • Xms =最小內(nèi)存分配池
    • Xmx =最大內(nèi)存分配池
    • XX:PermSize =將在JVM啟動期間分配的初始大小
    • XX:MaxPermSize = JVM啟動期間可以分配的最大大小

    11.如何對Java中的操作進(jìn)行計(jì)時(shí)

    Java中有兩種計(jì)時(shí)操作的標(biāo)準(zhǔn)方式: System.currentTimeMillis()System.nanoTime()問題是,選擇哪種方式以及在什么情況下。 原則上,它們都執(zhí)行相同的操作,但在以下方面有所不同:

  • System.currentTimeMillis需要大約1/1000秒到15/1000秒之間的時(shí)間(取決于系統(tǒng)),但是System.nanoTime()需要大約1 / 1000,000秒的時(shí)間(1,000納秒)
  • System.currentTimeMillis需要幾個(gè)時(shí)鐘周期來執(zhí)行讀取操作。 另一方面,System.nanoTime()需要100多個(gè)時(shí)鐘周期。
  • System.currentTimeMillis反映絕對時(shí)間(自1970年1月1日以來的毫秒數(shù)00:00(Epoch時(shí)間)),但是System.nanoTime()不一定代表任何參考點(diǎn)。
  • 12.浮動和雙精度之間的選擇

    數(shù)據(jù)類型 使用的字節(jié)數(shù) 有效數(shù)字(十進(jìn)制)
    浮動 4 7
    8 15

    在精度很重要的軟件中,Double通常優(yōu)于float,這是因?yàn)橐韵略?#xff1a;

    大多數(shù)處理器在Float和Double上執(zhí)行操作所需的處理時(shí)間幾乎相同。 Double在相同的計(jì)算時(shí)間內(nèi)提供了更高的精度。

    13.功率計(jì)算

    為了計(jì)算功效(^),java執(zhí)行異或(XOR)。 為了計(jì)算能力,Java提供了兩種選擇:

  • 乘法: double square = double a * double a; // Optimized double cube = double a * double a * double a; // Non-optimized double cube = double a * double square; // Optimized double quad = double a * double a * double a * double a; // Non-optimized double quad = double square * double square; // Optimized
  • pow(double base,double exponent): 'pow'方法用于計(jì)算不可能進(jìn)行乘法的地方(base ^ exponent) double cube = Math.pow(base, exponent);
  • 僅在必要時(shí)才使用Math.pow。 例如,指數(shù)是一個(gè)小數(shù)值。 這是因?yàn)镸ath.pow()方法通常比乘法慢300-600倍。

    14.如何處理空指針異常

    空指針異常在Java中很常見。 當(dāng)我們嘗試在空對象引用上調(diào)用方法時(shí),會發(fā)生此異常。 例如,

    int noOfStudents = school.listStudents().count;

    如果在上面的示例中,如果獲得NullPointerException,則school為null或listStudents()為Null。 盡早檢查Null是個(gè)好主意,這樣就可以消除它們。

    private int getListOfStudents(File[] files) {if (files == null)throw new NullPointerException("File list cannot be null");}

    15.用JSON編碼

    JSON(JavaScript對象表示法)是用于存儲和交換數(shù)據(jù)的語法。 JSON是XML的一種易于使用的替代方法。 如今,由于其特性和重量輕,Json在Internet上變得非常流行。 普通的數(shù)據(jù)結(jié)構(gòu)可以編碼為JSON,并可以輕松地在網(wǎng)頁上共享。 在開始編寫代碼之前,必須先安裝JSON解析器。 在以下示例中,我們使用了json.simple(https://code.google.com/p/json-simple/)。

    以下是編碼為JSON的基本示例:

    import org.json.simple.JSONObject; import org.json.simple.JSONArray;public class JsonEncodeDemo {public static void main(String[] args) {JSONObject obj = new JSONObject();obj.put("Novel Name", "Godaan");obj.put("Author", "Munshi Premchand");JSONArray novelDetails = new JSONArray();novelDetails.add("Language: Hindi");novelDetails.add("Year of Publication: 1936");novelDetails.add("Publisher: Lokmanya Press");obj.put("Novel Details", novelDetails);System.out.print(obj);} }

    輸出:

    {"Novel Name":"Godaan","Novel Details":["Language: Hindi","Year of Publication: 1936","Publisher: Lokmanya Press"],"Author":"Munshi Premchand"}

    16.從JSON解碼

    為了解碼JSON,開發(fā)人員必須了解該架構(gòu)。 可以在下面的示例中找到詳細(xì)信息:

    import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator;import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException;public class JsonParseTest {private static final String filePath = "//home//user//Documents//jsonDemoFile.json";public static void main(String[] args) {try {// read the json fileFileReader reader = new FileReader(filePath);JSONParser jsonParser = new JSONParser();JSONObject jsonObject = (JSONObject)jsonParser.parse(reader);// get a number from the JSON objectLong id = (Long) jsonObject.get("id");System.out.println("The id is: " + id); // get a String from the JSON objectString type = (String) jsonObject.get("type");System.out.println("The type is: " + type);// get a String from the JSON objectString name = (String) jsonObject.get("name");System.out.println("The name is: " + name);// get a number from the JSON objectDouble ppu = (Double) jsonObject.get("ppu");System.out.println("The PPU is: " + ppu);// get an array from the JSON objectSystem.out.println("Batters:");JSONArray batterArray= (JSONArray) jsonObject.get("batters");Iterator i = batterArray.iterator();// take each value from the json array separatelywhile (i.hasNext()) {JSONObject innerObj = (JSONObject) i.next();System.out.println("ID "+ innerObj.get("id") + " type " + innerObj.get("type"));}// get an array from the JSON objectSystem.out.println("Topping:");JSONArray toppingArray= (JSONArray) jsonObject.get("topping");Iterator j = toppingArray.iterator();// take each value from the json array separatelywhile (j.hasNext()) {JSONObject innerObj = (JSONObject) j.next();System.out.println("ID "+ innerObj.get("id") + " type " + innerObj.get("type"));}} catch (FileNotFoundException ex) {ex.printStackTrace();} catch (IOException ex) {ex.printStackTrace();} catch (ParseException ex) {ex.printStackTrace();} catch (NullPointerException ex) {ex.printStackTrace();}}}

    jsonDemoFile.json

    {"id": 0001,"type": "donut","name": "Cake","ppu": 0.55,"batters":[{ "id": 1001, "type": "Regular" },{ "id": 1002, "type": "Chocolate" },{ "id": 1003, "type": "Blueberry" },{ "id": 1004, "type": "Devil's Food" }],"topping":[{ "id": 5001, "type": "None" },{ "id": 5002, "type": "Glazed" },{ "id": 5005, "type": "Sugar" },{ "id": 5007, "type": "Powdered Sugar" },{ "id": 5006, "type": "Chocolate with Sprinkles" },{ "id": 5003, "type": "Chocolate" },{ "id": 5004, "type": "Maple" }] }The id is: 1 The type is: donut The name is: Cake The PPU is: 0.55 Batters: ID 1001 type Regular ID 1002 type Chocolate ID 1003 type Blueberry ID 1004 type Devil's Food Topping: ID 5001 type None ID 5002 type Glazed ID 5005 type Sugar ID 5007 type Powdered Sugar ID 5006 type Chocolate with Sprinkles ID 5003 type Chocolate ID 5004 type Maple

    17.簡單的字符串搜索

    Java提供了一個(gè)稱為indexOf()的Library方法。 此方法與String Object一起使用,它返回所需字符串的索引位置。 如果找不到該字符串,則返回-1。

    public class StringSearch {public static void main(String[] args) {String myString = "I am a String!";if(myString.indexOf("String") == -1) {System.out.println("String not Found!");}else {System.out.println("String found at: " + myString.indexOf("String"));}} }

    18.列出目錄的內(nèi)容

    為了列出目錄的內(nèi)容,可以使用以下程序。 該程序僅接收Array文件夾中所有子目錄和文件的名稱,然后順序遍歷該數(shù)組以列出所有內(nèi)容。

    import java.io.*;public class ListContents {public static void main(String[] args) {File file = new File("//home//user//Documents/");String[] files = file.list();System.out.println("Listing contents of " + file.getPath());for(int i=0 ; i < files.length ; i++){System.out.println(files[i]);}} }

    19.一個(gè)簡單的IO

    為了讀取文件并寫入文件,Java提供了FileInputStream和FileOutputStream類。 FileInputStream的構(gòu)造函數(shù)接受Input File的文件路徑作為參數(shù)并創(chuàng)建File Input Stream。 同樣,FileOutputStream的構(gòu)造函數(shù)接受Output File的文件路徑作為參數(shù)并創(chuàng)建File Output Stream。完成文件處理后,“關(guān)閉”流很重要。

    import java.io.*;public class myIODemo {public static void main(String args[]) throws IOException {FileInputStream in = null;FileOutputStream out = null;try {in = new FileInputStream("//home//user//Documents//InputFile.txt");out = new FileOutputStream("//home//user//Documents//OutputFile.txt");int c;while((c = in.read()) != -1) {out.write(c);}} finally {if(in != null) {in.close();}if(out != null) {out.close();}}} }

    20.從Java執(zhí)行shell命令

    Java提供了Runtime類來執(zhí)行Shell命令。 由于這些是外部命令,因此異常處理非常重要。 在下面的示例中,我們通過一個(gè)簡單的示例進(jìn)行說明。 我們正在嘗試從Shell命令打開PDF文件。

    import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader;public class ShellCommandExec {public static void main(String[] args) {String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";try {Runtime rt = Runtime.getRuntime();Process processObj = rt.exec(gnomeOpenCommand);InputStream stdin = processObj.getErrorStream();InputStreamReader isr = new InputStreamReader(stdin);BufferedReader br = new BufferedReader(isr);String myoutput = "";while ((myoutput=br.readLine()) != null) {myoutput = myoutput+"\n";}System.out.println(myoutput);}catch (Exception e) {e.printStackTrace();}} }

    21.使用正則表達(dá)式

    正則表達(dá)式構(gòu)造摘要(來源:Oracle網(wǎng)站)

    性格
    X 字符x
    \\ 反斜杠字符
    \ 0n 八進(jìn)制值0n(0 <= n <= 7)的字符
    \ 0nn 八進(jìn)制值0nn(0 <= n <= 7)的字符
    \ 0mnn 八進(jìn)制值0mnn的字符(0 <= m <= 3,0 <= n <= 7)
    \ xhh 十六進(jìn)制值為0xhh的字符
    \ uhhhh 十六進(jìn)制值為0xhhhh的字符
    \ x {h…h(huán)} 十六進(jìn)制值為0xh…h(huán)的字符(Character.MIN_CODE_POINT <= 0xh…h(huán) <= Character.MAX_CODE_POINT)
    \ t 制表符('\ u0009')
    \ n 換行符('\ u000A')
    \ r 回車符('\ u000D')
    \F 換頁字符('\ u000C')
    \一個(gè) 警報(bào)(響鈴)字符('\ u0007')
    \ e 轉(zhuǎn)義符('\ u001B')
    \ cx 與x對應(yīng)的控制字符

    角色類
    [abc] a,b或c(簡單類)
    [^ abc] 除a,b或c(取反)之外的任何字符
    [a-zA-Z] a到z或A到Z(含)(范圍)
    [ad [mp]] a到d,或m到p:[a-dm-p](聯(lián)合)
    [az && [def]] d,e或f(交叉點(diǎn))
    [az && [^ bc]] a到z,b和c除外:[ad-z](減法)
    [az && [^ mp]] a到z,而不是m到p:[a-lq-z](減法)

    預(yù)定義字符類
    任何字符(可能匹配也可能不匹配行終止符)
    \ d 一位數(shù)字:[0-9]
    \ D 非數(shù)字:[^ 0-9]
    \ s 空格字符:[\ t \ n \ x0B \ f \ r]
    \ S 非空白字符:[^ \ s]
    \ w 文字字符:[a-zA-Z_0-9]
    \ W 非文字字元:[^ \ w]

    邊界匹配器
    ^ 行的開頭
    $ 行尾
    \ b 單詞邊界
    \ B 非單詞邊界
    \一個(gè) 輸入的開始
    \G 上一場比賽的結(jié)束
    \ Z 輸入的結(jié)尾,但對于最終終止符(如果有)
    \ z 輸入的結(jié)尾
    import java.util.regex.Matcher; import java.util.regex.Pattern;public class RegexMatches {private static String pattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";private static Pattern mypattern = Pattern.compile(pattern);public static void main( String args[] ){String valEmail1 = "testemail@domain.com";String invalEmail1 = "....@domain.com";String invalEmail2 = ".$$%%@domain.com";String valEmail2 = "test.email@domain.com";System.out.println("Is Email ID1 valid? "+validateEMailID(valEmail1));System.out.println("Is Email ID1 valid? "+validateEMailID(invalEmail1));System.out.println("Is Email ID1 valid? "+validateEMailID(invalEmail2));System.out.println("Is Email ID1 valid? "+validateEMailID(valEmail2));}public static boolean validateEMailID(String emailID) {Matcher mtch = mypattern.matcher(emailID);if(mtch.matches()){return true;}return false;} }

    22.簡單的Java Swing示例

    借助Java Swing GUI可以創(chuàng)建。 Java提供了包含“ swing”的Javax。 使用swing的GUI從擴(kuò)展JFrame開始。 添加了框,以便它們可以包含GUI組件,例如Button,單選按鈕,文本框等。這些框設(shè)置在Container的頂部。

    import java.awt.*; import javax.swing.*; public class SwingsDemo extends JFrame { public SwingsDemo() {String path = "//home//user//Documents//images";Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); Box myHorizontalBox = Box. createHorizontalBox(); Box myVerticleBox = Box. createVerticalBox(); myHorizontalBox.add(new JButton("My Button 1")); myHorizontalBox.add(new JButton("My Button 2")); myHorizontalBox.add(new JButton("My Button 3")); myVerticleBox.add(new JButton(new ImageIcon(path + "//Image1.jpg"))); myVerticleBox.add(new JButton(new ImageIcon(path + "//Image2.jpg"))); myVerticleBox.add(new JButton(new ImageIcon(path + "//Image3.jpg"))); contentPane.add(myHorizontalBox); contentPane.add(myVerticleBox); pack(); setVisible(true);} public static void main(String args[]) { new SwingsDemo(); } }

    23.用Java播放聲音

    播放聲音是Java中的常見要求,尤其是與游戲一起使用時(shí)。

    本演示說明了如何播放音頻文件以及Java代碼。

    import java.io.*; import java.net.URL; import javax.sound.sampled.*; import javax.swing.*;// To play sound using Clip, the process need to be alive. // Hence, we use a Swing application. public class playSoundDemo extends JFrame {// Constructorpublic playSoundDemo() {this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setTitle("Play Sound Demo");this.setSize(300, 200);this.setVisible(true);try {URL url = this.getClass().getResource("MyAudio.wav");AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);Clip clip = AudioSystem.getClip();clip.open(audioIn);clip.start();} catch (UnsupportedAudioFileException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (LineUnavailableException e) {e.printStackTrace();}}public static void main(String[] args) {new playSoundDemo();} }

    24. PDF導(dǎo)出

    將表導(dǎo)出為PDF是Java程序中的常見要求。 使用itextpdf,導(dǎo)出PDF變得非常容易。

    import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter;public class DrawPdf {public static void main(String[] args) throws Exception {Document document = new Document();PdfWriter.getInstance(document, new FileOutputStream("Employee.pdf"));document.open();Paragraph para = new Paragraph("Employee Table");para.setSpacingAfter(20);document.add(para);PdfPTable table = new PdfPTable(3);PdfPCell cell = new PdfPCell(new Paragraph("First Name"));table.addCell(cell);table.addCell("Last Name");table.addCell("Gender");table.addCell("Ram");table.addCell("Kumar");table.addCell("Male");table.addCell("Lakshmi");table.addCell("Devi");table.addCell("Female");document.add(table);document.close();}}

    25.從Java代碼發(fā)送電子郵件

    從Java發(fā)送電子郵件很簡單。 我們需要安裝Java Mail Jar,并在程序的classpath中設(shè)置其路徑。 基本屬性是在代碼中設(shè)置的,我們很高興發(fā)送電子郵件,如下面的代碼所述:

    import java.util.*; import javax.mail.*; import javax.mail.internet.*;public class SendEmail {public static void main(String [] args){ String to = "recipient@gmail.com";String from = "sender@gmail.com";String host = "localhost";Properties properties = System.getProperties();properties.setProperty("mail.smtp.host", host);Session session = Session.getDefaultInstance(properties);try{MimeMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));message.setSubject("My Email Subject");message.setText("My Message Body");Transport.send(message);System.out.println("Sent successfully!");}catch (MessagingException ex) {ex.printStackTrace();}} }

    26.測量時(shí)間

    許多應(yīng)用需要非常精確的時(shí)間測量。 為此,Java在System類中提供了靜態(tài)方法:

  • currentTimeMillis():以“紀(jì)元時(shí)間”為單位,以毫秒為單位返回當(dāng)前時(shí)間(以毫秒為單位)。 long startTime = System.currentTimeMillis(); long estimatedTime = System.currentTimeMillis() - startTime;
  • nanoTime():返回最精確的可用系統(tǒng)計(jì)時(shí)器的當(dāng)前值(以納秒為單位)。 nanoTime()用于測量相對時(shí)間間隔,而不是提供絕對定時(shí)。 long startTime = System.nanoTime(); long estimatedTime = System.nanoTime() - startTime;
  • 27.重新縮放圖像

    可以使用AffineTransform重新縮放圖像。 首先,創(chuàng)建輸入圖像的圖像緩沖區(qū),然后渲染縮放圖像。

    import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO;public class RescaleImage {public static void main(String[] args) throws Exception {BufferedImage imgSource = ImageIO.read(new File("images//Image3.jpg"));BufferedImage imgDestination = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);Graphics2D g = imgDestination.createGraphics();AffineTransform affinetransformation = AffineTransform.getScaleInstance(2, 2);g.drawRenderedImage(imgSource, affinetransformation);ImageIO.write(imgDestination, "JPG", new File("outImage.jpg"));} }

    28.捕獲鼠標(biāo)懸停坐標(biāo)

    通過實(shí)現(xiàn)MouseMotionListner接口,可以捕獲鼠標(biāo)事件。 在特定區(qū)域中輸入鼠標(biāo)時(shí),將觸發(fā)MouseMoved事件,并可以捕獲運(yùn)動坐標(biāo)。 以下示例對此進(jìn)行了說明:

    import java.awt.event.*; import javax.swing.*;public class MouseCaptureDemo extends JFrame implements MouseMotionListener {public JLabel mouseHoverStatus;public static void main(String args[]) {new MouseCaptureDemo();}MouseCaptureDemo() {setSize(500, 500);setTitle("Frame displaying Coordinates of Mouse Motion");mouseHoverStatus = new JLabel("No Mouse Hover Detected.", JLabel.CENTER);add(mouseHoverStatus);addMouseMotionListener(this);setVisible(true);}public void mouseMoved(MouseEvent e) {mouseHoverStatus.setText("Mouse Cursor Coordinates => X:"+e.getX()+" | Y:"+e.getY());}public void mouseDragged(MouseEvent e) {} }

    FileWriter

    Java中的文件編寫主要通過兩種方式完成:FileOutputStream和FileWriter。 有時(shí),開發(fā)人員很難在其中選擇一個(gè)。 此示例幫助他們選擇在給定要求下應(yīng)使用哪個(gè)。 首先,讓我們看一下實(shí)現(xiàn)部分:

    使用FileOutputStream:

    File foutput = new File(file_location_string); FileOutputStream fos = new FileOutputStream(foutput); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fos)); output.write("Buffered Content");

    使用FileWriter:

    FileWriter fstream = new FileWriter(file_location_string); BufferedWriter output = new BufferedWriter(fstream); output.write("Buffered Content");

    根據(jù)Java API規(guī)范:

    FileOutputStream用于寫入原始字節(jié)流,例如圖像數(shù)據(jù)。 要編寫字符流,請考慮使用FileWriter。

    這清楚表明,對于圖像類型的數(shù)據(jù)應(yīng)使用FileOutputStream,對于文本類型的數(shù)據(jù)應(yīng)使用FileWriter。

    其他建議

  • 使用收藏

    Java附帶了一些收集類-例如,Vector,Stack,Hashtable,Array。 出于以下原因,鼓勵(lì)開發(fā)人員盡可能廣泛地使用集合:

    • 使用集合可以使代碼可重用和互操作。
    • 集合使代碼更結(jié)構(gòu)化,更易于理解和維護(hù)。
    • 開箱即用的集合類經(jīng)過了良好的測試,因此代碼質(zhì)量很好。
  • 10-50-500規(guī)則

    在大型軟件包中,維護(hù)代碼變得非常困難。 加入新的正在進(jìn)行的支持項(xiàng)目的開發(fā)人員經(jīng)常會抱怨: 整體式代碼 , Spaghetti代碼 。 有一個(gè)非常簡單的規(guī)則可以避免這種情況,或者保持代碼的干凈和可維護(hù):10-50-500。

    • 10:任何程序包都不能超過10個(gè)類。
    • 50:任何方法都不能超過50行代碼。
    • 500:沒有一個(gè)類可以包含超過500行代碼。
  • SOLID類設(shè)計(jì)原則

    SOLID(http://zh.wikipedia.org/wiki/SOLID_%28object-oriented_design%29)是Robert Martin提出的設(shè)計(jì)原則的首字母縮寫。 根據(jù)此規(guī)則:

    規(guī)則 描述
    單一責(zé)任原則 一堂課應(yīng)該只有一個(gè)任務(wù)/職責(zé)。 如果班級執(zhí)行的任務(wù)不止一項(xiàng),則會導(dǎo)致混亂。
    開閉原則 開發(fā)人員應(yīng)更多地專注于擴(kuò)展軟件實(shí)體,而不是對其進(jìn)行修改。
    里斯科夫替代原則 應(yīng)該可以用基類代替派生類。
    接口隔離原理 就像單一責(zé)任原則,但適用于接口。 每個(gè)接口應(yīng)負(fù)責(zé)一項(xiàng)特定任務(wù)。 開發(fā)人員應(yīng)該實(shí)現(xiàn)不需要的方法。
    依賴倒置原則 取決于抽象-但不取決于混凝土。 這意味著每個(gè)模塊都應(yīng)使用將它們綁定在一起的抽象層將它們分開。
  • 設(shè)計(jì)模式的使用

    設(shè)計(jì)模式可幫助開發(fā)人員在其軟件中納入最佳軟件設(shè)計(jì)原則。 它們還為全球的開發(fā)人員提供了通用平臺。 它們提供了標(biāo)準(zhǔn)術(shù)語,使開發(fā)人員能夠相互協(xié)作并更輕松地相互交流。

  • 記錄想法

    永遠(yuǎn)不要只是開始編寫代碼。 制定戰(zhàn)略,準(zhǔn)備,記錄,審查和實(shí)施。 首先,記下您的要求。 準(zhǔn)備設(shè)計(jì)文件。 適當(dāng)提及假設(shè)。 讓文檔經(jīng)過同行評審,并在其上簽字。

  • 在==上使用等于

    ==比較對象引用,它檢查兩個(gè)操作數(shù)是否指向相同的對象(不是等效的對象,相同的對象)。另一方面,“等于”執(zhí)行兩個(gè)字符串的實(shí)際比較。

  • 避免浮點(diǎn)數(shù)

    僅在絕對必要時(shí)才應(yīng)使用浮點(diǎn)數(shù)。 例如,使用浮點(diǎn)數(shù)表示盧比和帕斯可能會出現(xiàn)問題-應(yīng)該改用BigDecimal。 浮點(diǎn)數(shù)在測量中更有用。

  • 學(xué)習(xí)Java的最佳資源

    另外,我想提到有許多學(xué)習(xí)Java的資源 。

    翻譯自: https://www.javacodegeeks.com/2015/06/java-programming-tips-best-practices-beginners.html

    java 8入門與實(shí)踐

    總結(jié)

    以上是生活随笔為你收集整理的java 8入门与实践_30个Java入门技巧和最佳实践的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。