Java問題集錦

一、優先返回空集合而非nulljava

若是程序要返回一個不包含任何值的集合,確保返回的是空集合而不是null。這能節省大量的」if else」檢查。shell

二、謹慎操做字符串數據庫

若是兩個字符串在for循環中使用+操做符進行拼接,那麼每次循環都會產生一個新的字符串對象。這不只浪費內存空間同時還會影響性能。相似的,若是初始化字符串對象,儘可能不要使用構造方法,而應該直接初始化。比方說:json

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

三、避免無用對象數組

建立對象是Java中最昂貴的操做之一。所以最好在有須要的時候再進行對象的建立/初始化。以下:網絡

import java.util.ArrayList;
import java.util.List;

public class Employees {

    private List Employees;

    public List getEmployees() {

        //initialize only when required
        if(null == Employees) {
            Employees = new ArrayList();
        }
        return Employees;
    }
}

四、數組與ArrayList之爭session

開發人員常常會發現很難在數組和ArrayList間作選擇。它們兩者互有優劣。如何選擇應該視狀況而定。數據結構

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]; 
    }
}
  • 數組是定長的,而ArrayList是變長的。因爲數組長度是固定的,所以在聲明數組時就已經分配好內存了。而數組的操做則會更快一些。另外一方面,若是咱們不知道數據的大小,那麼過多的數據便會致使ArrayOutOfBoundException,而少了又會浪費存儲空間。性能

  • ArrayList在增刪元素方面要比數組簡單。優化

  • 數組能夠是多維的,但ArrayList只能是一維的。

五、判斷奇數

看下這幾行代碼,看看它們是否能用來準確地判斷一個數是奇數?

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

看似是對的,考慮到負奇數的狀況,它除以2的結果就不會是1。所以,返回值是false,而這樣是不對的。

代碼能夠修改爲這樣:

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

這麼寫不光是負奇數的問題解決了,而且仍是通過充分優化過的。由於算術運算和邏輯運行要比乘除運算更高效,計算的結果也會更快。

六、單引號與雙引號的區別

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

看起來這段代碼會返回」Haha」,但實際返回的是Ha169。緣由就是用了雙引號的時候,字符會被看成字符串處理,而若是是單引號的話,字符值會經過一個叫作基礎類型拓寬的操做來轉換成整型值。而後再將值相加獲得169。

七、一些防止內存泄露的小技巧

內存泄露會致使軟件的性能降級。因爲Java是自動管理內存的,所以開發人員並無太多辦法介入。不過仍是有一些方法可以用來防止內存泄露的。

  • 查詢完數據後當即釋放數據庫鏈接

  • 儘量使用finally塊

  • 釋放靜態變量中的實例

八、如何計算Java中操做的耗時

在Java中進行操做計時有兩個標準的方法:System.currentTimeMillis()和System.nanoTime()。問題就在於,什麼狀況下該用哪一個。從本質上來說,他們的做用都是同樣的,但有如下幾點不一樣:

  1. System.currentTimeMillis()的精度在千分之一秒到千分之15秒之間(取決於系統)而System.nanoTime()則能到納秒級。

  2. System.currentTimeMillis讀操做耗時在數個CPU時鐘左右。而System.nanoTime()則須要上百個。

  3. System.currentTimeMillis對應的是絕對時間(1970年1 月1日所經歷的毫秒數),而System.nanoTime()則不與任什麼時候間點相關。

  4. Float仍是double

  5. 數據類型 所用字節 有效位數
    float 4 7
    double 8 15
  6. 在對精度要求高的場景下,double類型相對float要更流行一些,理由以下:

  7. 大多數處理器在處理float和double上所需的時間都是差很少的。而計算時間同樣的前提下,double類型卻能提供更高的精度。

九、JSON編碼

JSON是數據存儲及傳輸的一種協議。與XML相比,它更易於使用。因爲它很是輕量級以及自身的一些特性,如今JSON在網絡上已是愈來愈流行了。常見的數據結構均可以編碼成JSON而後在各個網頁間自由地傳輸。不過在開始編碼前,你得先安裝一個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"}

十、JSON解析

開發人員要想解析JSON串,首先你得知道它的格式。下面例子有助於你來理解這一點:

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 file
            FileReader reader = new FileReader(filePath);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject)jsonParser.parse(reader);
            
            // get a number from the JSON object
            Long id =  (Long) jsonObject.get("id");
            System.out.println("The id is: " + id);           

            // get a String from the JSON object
            String   type = (String) jsonObject.get("type");
            System.out.println("The type is: " + type);

            // get a String from the JSON object
            String   name = (String) jsonObject.get("name");
            System.out.println("The name is: " + name);

            // get a number from the JSON object
            Double ppu =  (Double) jsonObject.get("ppu");
            System.out.println("The PPU is: " + ppu);
            
            // get an array from the JSON object
            System.out.println("Batters:");
            JSONArray batterArray= (JSONArray) jsonObject.get("batters");
            Iterator i = batterArray.iterator();
            // take each value from the json array separately
            while (i.hasNext()) {
                JSONObject innerObj = (JSONObject) i.next();
                System.out.println("ID "+ innerObj.get("id") + 
                        " type " + innerObj.get("type"));
            }

            // get an array from the JSON object
            System.out.println("Topping:");
            JSONArray toppingArray= (JSONArray) jsonObject.get("topping");
            Iterator j = toppingArray.iterator();
            // take each value from the json array separately
            while (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();
        }

    }

}

十一、列出目錄下的文件

你能夠用下面的代碼來列出目錄下的文件。這個程序會遍歷某個目錄下的全部子目錄及文件,並存儲到一個數組裏,而後經過遍歷數組來列出全部文件。

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]);
        }
    }
}
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();
            }
        }
    }
}

1三、在Java中執行某個shell命令

Java提供了Runtime類來執行shell命令。因爲這些是外部的命令,所以異常處理就顯得異常重要。在下面的例子中,咱們將經過一個簡單的例子來演示一下。咱們會在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();
        }
    }
}

1四、導出PDF文件

將表格導出成pdf也是一個比較常見的需求。經過itextpdf,導出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();
      }
    }

1五、郵件發送

在Java中發送郵件也很簡單。你只需裝一下Java Mail這個jar包,放到你的類路徑裏便可。在下面的代碼中,咱們設置了幾個基礎屬性,而後即可以發送郵件了:

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();
        }
    }
}
相關文章
相關標籤/搜索