Java Notes

AP Computer Science A

數字處理

  1. final = c++ 的 const
  2. error
public class test{ public static void main(String []args){ double a=1; int b=a; System.out.println(b); } }
  1. AC
public class test{ public static void main(String []args){ int a=1; double b=a; System.out.println(b);//1.0 } }
  1. others
public class test{ public static void main(String []args){ //double double a=(double)2/4+3; double b=(double)(2/4)+3; double c=(double)(2/4)+3.0; double d=(double)(2/4+3); double e=2/(double)4+3; double f=2/4.0+3; double g=2.0/4+3; //print System.out.println(a);//3.5 System.out.println(b);//3.0 System.out.println(c);//3.0 System.out.println(d);//3.0 System.out.println(e);//3.5 System.out.println(f);//3.5 System.out.println(g);//3.5 //int int h=(int)(4.0)/3; int i=(int)(4.0/3.0); int j=(int)4.0/3; System.out.println(h);//1 System.out.println(i);//1 System.out.println(j);//1 } }
  1. other error
public class test{ public static void main(String []args){ //int int a=(double)2/4+3; int b=(double)(2/4)+3; int c=(double)(2/4)+3.0; int d=(double)(2/4+3); //print System.out.println(a);//3.5 System.out.println(b);//3.0 System.out.println(c);//3.0 System.out.println(d);//3.0 } }

String

  1. equals
public class test{ public static void main(String []args){ //String String a="123",b="123",c="234"; System.out.println(a.equals(b));//true System.out.println(a.equals(c));//false System.out.println(new String("123").equals(new String ("123")));//true System.out.println(new String("123").equals(new String ("234")));//false System.out.println(a==b);//true System.out.println(a==c);//false //int error //int num1=1,num2=1; //System.out.println(num1.equals(num2)); } }
  1. compareTo
public class test{ public static void main(String []args){ String a="123",b="123",c="234"; System.out.println(a.compareTo(b));//0 System.out.println(a.compareTo(c));//-1 System.out.println(c.compareTo(a));//1 String A="A",B="B",C="C"; System.out.println(A.compareTo(B));//-1 System.out.println(C.compareTo(B));//1 System.out.println(C.compareTo(C));//0 } }
  1. length
public class test{ public static void main(String []args){ String a="123"; System.out.println(a.length());//3 } }
  1. substring
  • example 1
public class test{ public static void main(String []args){ String a="123",b="123456"; System.out.println(a.substring(1));//23 System.out.println(b.substring(2,4));//34 System.out.println(b.substring(5,6));//6 System.out.println(a+b.substring(6));//123 } }
  • example 2
public class test{ public static String abm(String a, String b){ int x=a.indexOf(b); while(x>=0){ System.out.println(a+" "+x); a=a.substring(0,x)+a.substring(x+b.length()); x=a.indexOf(b); System.out.println(a+" "+x); } return a; /* sing the song 2 si the song 9 si the song 9 si the so -1 si the so */ } public static void main(String []args){ String ans=abm("sing the song","ng"); System.out.println(ans);//si the so } }
  1. indexOf
public class test{ public static void main(String []args){ String a="123",b="123456"; System.out.println(a.indexOf("2"));//1 System.out.println(b.indexOf("45"));//3 System.out.println(b.indexOf("78"));//-1 } }

Math

  1. random
public class test{ public static void main(String []args){ // 0.0 <= a <= 1.0 double a=Math.random(); System.out.println(a); System.out.println((int)a); //lowvalue <= x <= highvalue int highvalue=10,lowvalue=2; double b=(highvalue-lowvalue)*Math.random()+lowvalue; int ans=(int)b; System.out.println(b); System.out.println(ans); } }
  1. other methods
public class test { public static void main(String[] args) { double a=Math.pow(3,2); System.out.println(a);//9.0 double b=Math.abs(-2); System.out.println(b);//2.0 double c=Math.sqrt(9); System.out.println(c);//3.0 System.out.println(Math.PI);//3.141592653589793 System.out.println(Math.E);//2.718281828459045 } }

Array & Array List

  1. Array
public class test{ public static void main(String []args){ int[] arr = new int[5]; for(int i=0;i<5;i++){ arr[i]=i+1; } for(int i=0;i<5;i++){ System.out.print(arr[i]+" ");//1 2 3 4 5 } System.out.println(); System.out.println(arr.length);//5 } }
  1. Array List
import java.util.ArrayList; public class test{ public static void main(String []args){ ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); System.out.println(list);//[1] System.out.println(list.size());//1 System.out.println(list.get(0));//1 list.set(0,2); System.out.println(list.get(0));//2 list.add(1,4); list.add(1,3); System.out.println(list);//[2,3,4] list.add(5); System.out.println(list);//[2,3,4,5] System.out.println(list.contains(2));//true System.out.println(list.contains(1));//false System.out.println(list.indexOf(3));//1 list.remove(1); System.out.println(list);//[2,4,5] list.clear(); System.out.println(list);//[] } }

Class

class cellphone{ double screensize; void call(){ System.out.println("The screensize is "+screensize); } } public class test{ public static void main(String []args){ cellphone iphone = new cellphone(); iphone.screensize = 2.0; iphone.call();//The screensize is 2.0 } }

extends & polymorphism 多態性 & implements

class Student{ private int score; private double gpa; public Student(){ score=0; gpa=0.0; } public Student(int s, double g){ score = s; gpa = g; } public double getGPA(){ return gpa; } public int getScore(){ return score; } public void printGPA(){ System.out.println("My GPA is "); } public String test(){ return "A"; } public void showtest(){ System.out.println(test()); } } interface Two{ public void print();//abstract } class One implements Two{ public void print(){ System.out.println("I'm implements."); } } interface Three{ public void print();//abstract } class highstudent extends Student implements Three{ private double rent; public highstudent(){ super();//Student() rent=0.0; } public highstudent(int s, double g, double r){ super(s,g);//Student(int s, double g) rent = r; } public double getGPA(){ return super.getGPA(); } public int getScore2(){ return getScore(); } public double getRent(int pass){ if(pass==1234){ return rent; } return -1; } public void printGPA(){ System.out.println(getGPA()); } public void print(){ System.out.println("I'm implements from extends."); } public String test(){ return "B"; } } public class test{ public static void main(String []args){ //extends highstudent Peter = new highstudent(); System.out.println(Peter.getGPA());//0.0 System.out.println(Peter.getScore2());//0 highstudent Wang = new highstudent(100,4.8,10); System.out.println(Wang.getGPA());//4.8 System.out.println(Wang.getScore2());//100 System.out.println(Wang.getRent(123));//-1.0 System.out.println(Wang.getRent(1234));//10.0 //polymorphism Student Tim = new Student();//valid Student Allison = new highstudent();//valid //highstudent Christine = new Student();//invalid, compile error Tim.printGPA();//My GPA is Allison.printGPA();//0.0 Allison.showtest();//B 優先使用子類函數 //Allison.print();//compile error 父類引用指向子類函數不允許使用父類不存在的方法 //implements Two twostudent = new One(); twostudent.print();//I'm implements. Three threestudent = new highstudent(); threestudent.print();//I'm implements from extends. } }

sorting

selection sort

最小放第一個,第二小放第二個,依此類推

insertion sort

將資料分為” 已排序 “ 和 “ 未排序 “,將未排序的第一筆值和已排序的資料由右而左相比大小並插入適當位置。

merge sort

將資料分割為左子樹以及右子樹,接著遞迴分割每一次分割後的左子樹以及右子樹,直到每個子樹只剩下一個元素,再將這些子樹依小到大(or 大到小)合併(Merge)。

CSE 123

Section 0 Warm up

Array versus ArrayList

  1. Print
import java.util.*;

public class test {
    public static void main(String[] args) {
        int[] arr = new int[10];
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i<10; i++) {
            arr[i] = i;
            list.add(i);
        }
        System.out.println(Arrays.toString(arr)); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    }
}
  1. Length and Size
import java.util.*;

public class TwoDArray {
    public static void main(String[] args) {
        int rows = 4;
        int columns = 6;
 
        int[][] array = new int[rows][columns];
        ArrayList<Integer> list = new ArrayList<>();
        
        System.out.println(list.size()); // 0
        System.out.println(array[0].length); // 6
    }
}

Programming Assignment 0

Map

HashMap vs. TreeMap
  1. Ordering:
  • HashMap: Entries in a HashMap are not ordered in any specific way. There is no guarantee of the order in which elements were added or any natural ordering of the keys.
  • TreeMap: Entries in a TreeMap are sorted based on their keys. By default, they are sorted in natural order or according to a specified comparator. This means that the keys are always sorted in the map.
  1. Performance:
  • HashMap: Offers faster average-case performance for basic operations like insertion, deletion, and retrieval (O(1) on average). However, this may not hold true in all cases, as performance depends on the quality of the hash function and collision resolution strategy.
  • TreeMap: Provides O(log n) time complexity for basic operations, which makes it slower than HashMap. However, this logarithmic time complexity is more predictable and consistent regardless of the distribution of keys.
  1. Null Keys:
  • HashMap: Allows one null key. This means you can have one key-value pair with a null key in a HashMap.
  • TreeMap: Does not allow null keys. Attempting to insert a null key will result in a NullPointerException.
  1. Custom Sorting:
  • HashMap: Does not provide built-in support for custom sorting. Keys are inserted based on their hash code, and their order is not controlled by the developer.
  • TreeMap: Allows you to specify a custom comparator to control the order of keys. This enables you to sort keys in a custom way.
  1. Memory Usage:
  • HashMap: Typically consumes less memory compared to TreeMap because it does not need to maintain the sorted order of keys.
  • TreeMap: Consumes more memory due to the overhead of maintaining a balanced tree structure to keep keys sorted.
Map methods

Set

Set methods

Queue

Queue methods

Stack

Stack methods

pre class work 1

pre class work 2

Pre-Condition

Accepted range of input

Post-Condition

Expected Output

Exception

Some important exceptions we will see and use throughout CSE 123 include

  • NullPointerException
  • IllegalArgumentException
  • ArrayIndexOutOfBoundsException
  • ClassCastException