Java Basic
Null 和 0 的差異
List a == null
是指List位址是空,而List a == 0
是List 位址為0xFDJJLJDKLASJDLA,空間已經開出來了裡面卻沒放東西
Prefix-increment and post increment 前置遞增和後置遞增的差異
public class UnaryOperatorDemo {
public static void main(String[] args) {
int age = 10;
int var = age++;
System.out.println(age);
System.out.println(var);
}
}
age++
是後置算法,等同於
var = age;
age = age + 1;
age
先指定給value
後才遞增,所以輸出是11, 10
overloading & overriding
overloading: 藉由接收的參數串列之型態或數量之不同,以求達到多個函式可共用相同函式名稱 (回傳值可不同)。目的為降低所需命名的函式名稱
void print(int i) {…}
void print(double d) {…}
void print(char c) {...}
overriding: 子類別將父類別函式重新定義以符合自身所需(回傳值必須相同)。目的為利用父類別來動態操作子類別的函式,以達多型的效果。
class Person {
public void iam()
{System.out.println(“I am a person.”);}
}
class Superman extends Person {
public void iam()
{System.out.println(“I am a Superman.”);}
}
記憶體
Java中-128到127之間在裝箱後會存在記憶體中被重複使用。以外的值則是程式在運行時才會建立一個新的物件
比較兩個物件大小必須使用
equals()
,使用==
則是比較兩個物件是否比較到同一個參考名稱
Class使用方式比較

Random
Random ran = new Random();
int r = ran.nextInt(n) // create number 0~(n-1)
String 經常變動使用 StringBuilder
public static String intToString(int x){
boolean isNegtive = false;
if (x<0)
isNegtive = true;
x = -x;
}
StringBuilder s = new StringBuilder();
while(x != 0){
s.append((char)('0'+ x%10))}
x /= 10;
if (Negtive){
s.append('-');
}
s.reverse();
return s.toString();
}
Comparator and Comparable
Comparable: 類別本身繼承comparable,改寫compareTo,實現在類別內部
public class Student implements Comparable {
String name;
int age
public int compareTo(Student another) {
int i = 0;
i = name.compareTo(another.name);
if(i == 0) {
return age - another.age;
} else {
return i;
}
}
}
// 可以使用Collections.sort(StudentList)排序
Comparator: 指定comparator告知類別如何排序,改寫compare,實現在類別外部
public class Student{
String name;
int age
}
class StudentComparator implements Comparator {
public int compare(Student one, Student another) {
int i = 0;
i = one.name.compareTo(another.name);
if(i == 0) {
return one.age - another.age;
} else {
return i; }
}
}
//Collections.sort(StudentList , new StudentComparator())
//指定comparator
使用binarySearch必須指定Comparator
Collection.binarySearch(Object, target, CompGPA)
private static Comparator<student> compGPA = new Comparator<student>(){
public int compare(student s1, student s2){
};
Last updated
Was this helpful?