Java

運算子

參考資料:(https://openhome.cc/Gossip/Java/Operator.html)

算數運算子

+ , - , * , /

% 模數運算子 或稱為 餘除運算子

比較、條件運算子

> , < , >= , <= , == , !=

算出來的結果以 boolean 表示

條件式 ? 成立回傳值 : 失敗回傳值

邏輯運算子

AND --> &&

OR --> ||

NOT --> !

&&|| 有所謂的捷徑運算

if(b != 0 && a / b > 5) //利用捷徑運算去避免 除0 錯誤

位元運算子

and --> &

or --> |

xor --> ^

左移 --> <<

右移 --> >>

遞增、遞減運算子

++

--

指定運算子

=

除了=,算數運算子、位元運算子 後面加等號 ,也是指定運算子

重寫和重載之間的區別\

參考資料:(http://www.runoob.com/java/java-override-overload.html)

區別點

重載方法(Overload)(多型)

重寫方法(Override)(父子關係的改寫)

參數列表

必須修改

不能修改

返回類型

可以修改

不能修改

異常

可以修改

可以減少或刪除,但是不能新增跟原先不同的異常

訪問

可以修改

不能做更嚴格的限制(可以降低限制)

Java – How to convert File to byte[]

參考資料:(https://www.mkyong.com/java/how-to-convert-file-into-an-array-of-bytes/)

File file = new File("/temp/abc.txt");
//init array with file length
byte[] bytesArray = new byte[(int) file.length()]; 

FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();

return bytesArray;

or NIO

String filePath = "/temp/abc.txt";

byte[] bFile = Files.readAllBytes(new File(filePath).toPath());
//or this
byte[] bFile = Files.readAllBytes(Paths.get(filePath));

判斷null

參考資料:(https://blog.csdn.net/yongh701/article/details/47109337)

判斷null 的方法,只能執行下列這種

if(obj == null){
   //something
}

包括 obj.equals(null) 都會 NullPointerException

String str = null;

String str1 = "";

也是不一樣的,前者就真的是null。後者是有實體的,可以調用 .isEmpty 來判斷是否為空

判斷String 是否為空 or Null 的較好方法

參考資料:(http://luckyboy7527.pixnet.net/blog/post/102390946-[java]null或空值時的判斷處理方法(較好的方法))

if (!"".equals(str)) { //do something }

這樣不管該字串是null 還是 "" 都可以達到檢查效果

判斷類別

參考資料:(https://www.artima.com/intv/bloch17.html)

參考資料:(https://stackoverflow.com/questions/4989818/instanceof-vs-getclass)

得到類型

根據需求決定要用下列何者,過度使用任何一種,都會導致 design smell

想要完全匹配

obj.getClass() ==

想要 左側 的繼承關係可以追溯到 右側

if(obj instanceof String){
   //something
}

Equal 中的上兩者

參考資料:(https://medium.com/@akash746/instanceof-vs-getclass-in-equals-method-in-java-3e90ec60a9cc)

對double做處理

保留到第二位

參考資料:(http://violin-tao.blogspot.com/2014/06/java-double.html)

double d1 = 3.14159;
double d2 = 1.5763;
DecimalFormat df = new DecimalFormat("##.00");
d1 = Double.parseDouble(df.format(d1));
d2 = Double.parseDouble(df.format(d2));

[結果] d1 印出來:3.14 d2 印出來:1.58

保留2位小數 + 四捨五入

參考資料:(https://blog.csdn.net/u011595939/article/details/53005984)

double f = 23.456;
BigDecimal bigDecimal = new BigDecimal(f);
//這裡的2決定要保留幾位
double f1 = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

Date

Date()

Date(long millisec)

Date date = new Date(); //當前時間

String 與 Date 互轉

格式化日期 Date --> String

y   year of era
D   day of year
M   month of year
d   day of month

Y   week based year
w   week of week based year
W   week of month
E   day of week

a   am pm of day
h   clock hour of am pm
K   hour of am pm
k   clock hour of am pm

H   hour of day
m   minute of hour
s   second of minute
S   fraction of second

V   time zone ID
z   time zone name
O   localized zone offset
  1. SimpleDateFormat

Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd"); //format string

System.out.println("Current Date : " + ft.format(date));
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyMMddHHmmss");
String date = LocalDateTime.now().format(dtf);

String --> Date

參考資料:(https://yunnick.iteye.com/blog/1074495)

String str = "2010/03/24 12:34:56";
Date date = new Date();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //要注意字串跟格式要匹配

try{
   date = sdf.parse(str);
   System.out.println(date.toString());
}catch(Exception e){
   e.printStackTrace();
}

String 與 Timestamp 互轉

String --> Timestamp

//注意字串格式一定要是 yyyy-mm-dd hh:mm:ss[.f...] 這樣的格式 //不然就先解析、重組成這樣的格式 String str = "2011-05-09 11:49:45"; Timestamp ts = new Timestamp(System.currentTimeMillis()); try{ ts = Timestamp.valueOf(str); System.out.println(ts); }catch(Exception e){ e.printStackTrace(); }

Time --> String

Timestamp ts = new Timestamp(System.currentTimeMillis());  
String tsStr = "";  
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
try {  
   //方法一  
   tsStr = sdf.format(ts);  
   System.out.println(tsStr);  
   //方法二  
   tsStr = ts.toString();  
   System.out.println(tsStr);  
} catch (Exception e) {  
   e.printStackTrace();  
}

方法一的好處,在於可以靈活的設置 String 的格式。

Date 與 Timestamp 互轉

這兩者是父子類關係

子類可以轉父類

但是父類不能只接轉子類,可以藉由String 去當中介。

Timestamp --> Date

Timestamp ts = new Timestamp(System.currentTimeMillis());  
Date date = new Date();  
try {  
   date = ts;  
   System.out.println(date);  
} catch (Exception e) {  
   e.printStackTrace();  
}

Date --> Timestamp

利用String 當中介

or

Timestamp ts = new Timestamp(date.getTime());

Date 與 LocalDateTime 互轉

參考資料:(https://blog.csdn.net/hspingcc/article/details/73332380)

Date --> LocalDateTime

Date date = new Date();
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();

LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
System.out.println("Date = " + date);
System.out.println("LocalDateTime = " + localDateTime);

LocalDateTime --> Date

ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zdt = localDateTime.atZone(zoneId);

Date date = Date.from(zdt.toInstant());

System.out.println("LocalDateTime = " + localDateTime);
System.out.println("Date = " + date);

Convert Long into Integer

參考資料:(https://stackoverflow.com/questions/5804043/convert-long-into-integer)

這個寫法,如果溢位會丟 Exception

Integer i = theLong == null ? null : Math.toIntExact(theLong);

獲取Java物件中所有的屬性名稱和屬性值

參考資料:(https://www.itread01.com/content/1547419865.html)

取得所有屬性

Field[] fields=o.getClass().getDeclaredFields();

取得該屬性的值

/* 根據屬性名獲取屬性值  
     * */  
    private static Object getFieldValueByName(String fieldName, Object o) {  
        try {    
            String firstLetter = fieldName.substring(0, 1).toUpperCase();    
            String getter = "get" + firstLetter + fieldName.substring(1);    
            Method method = o.getClass().getMethod(getter, new Class[] {});    
            Object value = method.invoke(o, new Object[] {});    
            return value;    
        } catch (Exception e) {    
          
            return null;    
        }    
    }  

Last updated