發現現在的天下幾乎都是java的天下啊,雖然我個人對java沒什么好感,但是迫於生活壓力,還是學一下吧,我關注的應該主要還是web方面,所以應該學的是
java server page(JSP),所以先把javase的內容先復習復習一下吧。
我覺得通過一些demo來記語言中的一些特性和概念是比較好的,所以我總結了以下的Demo:(這只是對我個人而言比較薄弱的部分,並不能代表大部分人的看法,謝謝!)
1.一維數組與多維數組

package Demo; public class Array { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //新建一個10元素的數組 int[] a = new int[10]; for(int i = 0;i < 10;i++){ a[i] = i; } System.out.println("改變前:" ); for(int i = 0;i < 10;i++){ System.out.print(a[i]+" "); } System.out.printf("\n"); a = reserve1(a); System.out.println("reserve1后:"); for(int i = 0;i < 10;i++){ System.out.print(a[i]+" "); } System.out.printf("\n"); reserve2(a); System.out.println("reserve2后:"); printArray(a); //二維數組的特性 int[][] a2 = { {1,2,3}, {2,3}, {1,2,3} }; int i; System.out.println("a2 is " + a2.length); for(i = 0;i < a2.length;i++){ System.out.println(i+" is "+a2[i].length); } } //從方法中返回數組 public static int[] reserve1(int[] list){ int[] result = new int[list.length]; for(int i = 0,j = result.length-1;i < list.length;i++,j--){ result[j] = list[i]; } return result; } //直接處理:引用傳遞 public static void reserve2(int[] list){ int temp; for(int i = 0,j = list.length - 1;i < list.length / 2;i++,j--){ temp = list[i]; list[i] = list[j]; list[j] = temp; } } //可變長的參數列表 public static void printArray(int... num){ if(num.length == 0){ System.out.println("No 參數!"); } else{ for(int i = 0;i < num.length;i++){ System.out.print(num[i] + " "); } System.out.print("\n"); } } }
2.對象與類
注意:包內訪問與包外訪問(包外訪問加上:import packet.class_name):

1 /*TTV.java*/ 2 package Home; 3 import Home2.STV; 4 import Home2.Date; 5 6 public class TTV { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 STV tv1 = new STV(); 14 tv1.turnOn(); 15 tv1.setChannel(30); 16 tv1.setVolume(3); 17 18 STV tv2 = new STV(); 19 tv2.turnOn(); 20 tv2.channelUp(); 21 tv2.channelUp(); 22 tv2.volumeUp(); 23 24 System.out.println("tv1's channel is" + tv1.channel 25 + " and volume level is " + tv1.volumeLevel); 26 System.out.println("tv2's channel is" + tv2.channel 27 + " and volume level is " + tv2.volumeLevel); 28 System.out.println("count1 = " + tv1.numplus()); 29 System.out.println("count2 = " + tv1.numplus()); 30 System.out.println("count3 = " + tv2.numplus()); 31 32 } 33 34 } 35 36 /*STV.java*/ 37 package Home2; 38 39 public class STV { 40 public int channel = 1; 41 public int volumeLevel = 1; 42 public boolean on = false; 43 public static int num = 0; 44 public STV(){ 45 46 } 47 public static int numplus(){ 48 num++; 49 return num; 50 } 51 public void turnOn(){ 52 on = true; 53 } 54 55 public void turnOff(){ 56 on = false; 57 } 58 59 public void setChannel(int newChannel){ 60 if(on && newChannel >= 1 && newChannel <= 120) 61 channel = newChannel; 62 } 63 64 public void setVolume(int newVolumeLevel){ 65 if(on && newVolumeLevel >= 1 && newVolumeLevel <= 7){ 66 volumeLevel = newVolumeLevel; 67 } 68 } 69 70 public void channelUp(){ 71 if(on && channel < 120) 72 channel++; 73 } 74 75 public void channelDown(){ 76 if(on && channel >1){ 77 channel--; 78 } 79 } 80 81 public void volumeUp(){ 82 if(on && volumeLevel < 7){ 83 volumeLevel++; 84 } 85 } 86 87 public void volumeDown(){ 88 if(on && volumeLevel > 1){ 89 volumeLevel--; 90 } 91 } 92 }
this引用:指向調用對象本身得引用名。
靜態方法才能修改靜態變量。
package Demo; public class Foo { int i = 5; static double k = 0; public static void main(String[] args){ Foo f = new Foo(); f.setK(2.0); System.out.println("k = " + k); } void setI(int i){ this.i = i; } public static void setK(double k){ Foo.k = k; } }
3.繼承與多態
在繼承關系中,構造函數無法覆蓋,類只能單一繼承。注意下面例子:
注意動態綁定:

package Home2; public class Date extends Date1{ public static void main(String[] args){ Date d1 = new Date("1"); System.out.println(d1.getNum(3)); //下面上動態綁定的結果 System.out.println("動態綁定: "); Date1 d2 = new Date(); } public Date(){ System.out.println("(1)"); } public Date(String s){ super("4"); System.out.println(s); } //終極函數,意味着不能再被擴展 public final int getNum(int a){ return super.getNum(a); } } class Date1{ public Date1(){ System.out.println("(2)"); } public Date1(String s){ System.out.println(s); } public int getNum(int a){ return 2*a; } } class Date2{ public Date2(){ System.out.println("(5)"); } }
數據和方法的可見性
類中成員的修飾符 | 在同一類內訪問 | 在同一包內訪問 | 在子類內可訪問 | 在不同包可訪問 |
public | Y | Y | Y | Y |
protected | Y | Y | Y | - |
default(不用填也不能填的默認屬性 | Y | Y | - | - |
private | Y | - | - | - |
防止擴展和覆蓋:final
終極類:public final class
終極方法:public final void m()
常量:static final PI = 3.1415926;
4.抽象類和接口
抽象類:類的設計應該確保父類包含它的子類的共同特征。有時候,一個父類設計得非常抽象,以至於它都沒有任何具體的實例。抽象類的構造函數的默認屬性是protected。
接口:為了定義多個類(特別是不相關的類)的共同行為。
接口與抽象類
變量 | 構造方法 | 方法 | |
抽象類 | 無限制 | 子類通過構造方法鏈調用構造方法, 抽象類不能用new操作符實例化 |
無限制 |
接口 | 所有的變量必須是 public static final |
沒有構造方法。 接口不能用new操作符實例化。 |
所有方法必須是公共的抽象實例方法 |
Java只允許為類的擴展做單一繼承,但是允許使用接口做多重擴展。
抽象類Demo:
package Demo; public class TestAnimal { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Animal animal = new Chicken(); eat(animal); animal = new Duck(); eat(animal); } public static void eat(Animal animal){ System.out.println(animal.howToEat()); } } abstract class Animal{ public abstract String howToEat(); } class Chicken extends Animal{ public String howToEat(){ return "Chicken"; } } class Duck extends Animal{ public String howToEat(){ return "Duck"; } }
接口Demo:
1 package Demo; 2 3 public class TestInterface { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Edible stuff = new Chicken(); 11 Edible1 stuff1 = new Broccoli(); 12 eat(stuff); 13 14 stuff = new Duck(); 15 eat(stuff); 16 17 stuff = new Broccoli(); 18 eat(stuff); 19 sleep(stuff1); 20 } 21 22 public static void eat(Edible stuff){ 23 System.out.println(stuff.howToEat()); 24 } 25 26 public static void sleep(Edible1 stuff1){ 27 System.out.println(stuff1.howToSleep()); 28 } 29 } 30 31 interface Edible{ 32 public String howToEat(); 33 34 } 35 36 interface Edible1{ 37 public String howToSleep(); 38 } 39 40 class Chicken implements Edible{ 41 public String howToEat(){ 42 return "Chicken"; 43 } 44 } 45 46 class Duck implements Edible{ 47 public String howToEat(){ 48 return "Duck"; 49 } 50 } 51 52 class Broccoli implements Edible,Edible1{ 53 public String howToEat(){ 54 return "Broccoli"; 55 } 56 57 public String howToSleep() { 58 // TODO Auto-generated method stub 59 return "Sleep"; 60 } 61 }
5.文本I/O
一.File類的基本函數
package Demo; public class TestFileClass { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub java。io.File file = new java.io.File("image/gif"); System.out.println("Does it exist? "+file.exists()); System.out.println("The file has " + file.length() + " bytes"); System.out.println("can it be read? " + file.canRead()); System.out.println("can it be written? " + file.canWrite()); System.out.println("Is it a directory? " + file.isDirectory()); System.out.println("Is it a file? " + file.isFile()); System.out.println("Is it absolute? " + file.isAbsolute()); System.out.println("Is it a Hidden? " + file.isHidden()); System.out.println("Absolute path is " + file.getAbsolutePath()); System.out.println("Last modified on " + new java.util.Date(file.lastModified())); } }
二.使用PrintWriter寫數據
package Demo; public class WriteData { /** * @param args */ public static void main(String[] args) throws Exception { //拋出異常 // TODO Auto-generated method stub java.io.File file = new java.io.File("score.txt"); //建立文件對象 if(file.exists()){ System.out.println("File already exist"); System.exit(0); } java.io.PrintWriter output = new java.io.PrintWriter(file); output.print("Hello!My id is "); output.print(11365020); output.println("!"); //close output.close(); } }
三.使用Scanner讀數據
package Demo; import java.util.Scanner; public class ReadData { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub java.io.File file = new java.io.File("score.txt"); Scanner input = new Scanner(file); while(input.hasNext()){ String firname = input.next(); String mi = input.next(); int score = input.nextInt(); System.out.println(firname + mi + score); } input.close(); } }
注意:方法next()和nextLine()都會讀取一個字符串,next()方法讀取一個由分隔符分隔的字符串,但是nextLine()讀取一個以行分隔符結束的行。
6.泛型
一.定義泛型類和接口
1 //GenericStack.java 2 package Demo; 3 4 public class GenericStack { 5 6 private java.util.ArrayList<E> list = new java.util.ArrayList<E>(); 7 8 public int getSize(){ 9 return list.size(); 10 } 11 12 public E peek(){ 13 return list.get(getSize() - 1); 14 } 15 16 public void push(E o){ 17 list.add(o); 18 } 19 20 public E pop(){ 21 E o = list.get(getSize() - 1); 22 list.remove(getSize() - 1); 23 return o; 24 } 25 26 public boolean isEmpty(){ 27 return list.isEmpty(); 28 } 29 }
7.Java集合框架
關於java的集合框架,建議還是查一下文檔,其實和C++的STL庫差不多,只是功能上可能豐富了一點。下面介紹幾個常用的:
一.Collection接口
二.Set接口
Set接口擴展了Collection接口。它沒有引入新的方法或常量,只是規定Set實例不包含重復的元素。
(1).散列集HashSet

package Demo; import java.util.*; public class TestHashSet { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Set<String> set = new HashSet<String>(); //添加元素 set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Franciso"); set.add("New York"); System.out.println(set); //迭代器迭代 Iterator<String> iterator = set.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next().toUpperCase() + " "); } } }
(2).鏈式散列集LinkedHashSet
LinkedHashSet用一個鏈表實現來擴展HashSet類,它支持對規則集內的元素排序。

package Demo; import java.util.*; public class TestLinkedHashSet { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Set<String> set = new LinkedHashSet<String>(); //添加元素 set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Franciso"); set.add("Beijing"); set.add("New York"); System.out.println(set); //使用for-each循環 for(Object element:set) System.out.println(element.toString().toLowerCase() + " "); } }
(3).樹形集TreeSet

package Demo; import java.util.*; public class TestTreeSet { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Set<String> set = new HashSet<String>(); set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); TreeSet<String> treeSet = new TreeSet<String>(set); System.out.println("Sorted tree set: " + treeSet); System.out.println("first()" + treeSet.first()); System.out.println("last()" + treeSet.last()); System.out.println("headSet(): " + treeSet.headSet("New York")); System.out.println("tailSet(): " + treeSet.tailSet("New York")); System.out.println("lower(\"P\"): " + treeSet.lower("P")); System.out.println("higher(\"P\"): " + treeSet.higher("P")); System.out.println("floor(\"P\"): " + treeSet.floor("P")); System.out.println("ceiling(\"P\"): " + treeSet.ceiling("P")); System.out.println("pollFirst(): " + treeSet.pollFirst()); System.out.println("pollLast() : " + treeSet.pollLast()); System.out.println("New tree set: " + treeSet); } }
三.List接口
List接口增加了面向位置的操作,並且增加了一個能夠雙向遍歷線性表的新列表迭代器。
(1).數組線性表ArrayList和鏈表類LinkedList

package Demo; import java.util.*; public class TestArrayAndLinkedList { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(1); arrayList.add(2); arrayList.add(3); arrayList.add(1); arrayList.add(4); arrayList.add(0,10); arrayList.add(3,30); System.out.println("A list of integers in the array list:"); System.out.println(arrayList); LinkedList<Object> linkedList = new LinkedList<Object>(arrayList); linkedList.add(1,"red"); linkedList.removeLast(); linkedList.addFirst("green"); System.out.println("Display the linked list forward:"); ListIterator<Object> listIterator = linkedList.listIterator(); while(listIterator.hasNext()){ System.out.print(listIterator.next() + " "); } System.out.println("Display the linked list backward:"); listIterator = linkedList.listIterator(linkedList.size()); while(listIterator.hasPrevious()){ System.out.print(listIterator.previous() + " "); } } }
四.向量類Vector與棧類Stack
五.隊列與優先隊列
Queue擴展的是Collection:
package Demo; public class TestQueue { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub java.util.Queue<String> queue = new java.util.LinkedList<String>(); queue.offer("Oklahoma"); queue.offer("Indiana"); queue.offer("Georgia"); queue.offer("Texas"); while(queue.size() > 0) System.out.print(queue.remove() + " "); } }
優先隊列:PriorityQueueDemo
1 package Demo; 2 3 import java.util.*; 4 5 public class PriorityQueueDemo { 6 7 /** 8 * @param args 9 */ 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 PriorityQueue<String> queue1 = new PriorityQueue<String>(); 13 queue1.offer("Oklahoma"); 14 queue1.offer("Indiana"); 15 queue1.offer("Georgia"); 16 queue1.offer("Texas"); 17 18 System.out.println("Priority queue using Comparable:"); 19 while(queue1.size() > 0){ 20 System.out.print(queue1.remove() + " "); 21 } 22 23 PriorityQueue<String> queue2 = new PriorityQueue<String>(4,Collections.reverseOrder()); 24 queue2.offer("Oklahoma"); 25 queue2.offer("Indiana"); 26 queue2.offer("Georgia"); 27 queue2.offer("Texas"); 28 29 System.out.println("\nPriority queue using Comparable:"); 30 while(queue2.size() > 0){ 31 System.out.print(queue2.remove() + " "); 32 } 33 } 34 35 }
六.圖
圖分三種,見以下代碼:

package Demo; import java.util.*; public class TestMap { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Map<String,Integer> hashMap = new HashMap<String,Integer>(); hashMap.put("Smith", 30); hashMap.put("Anderson", 31); hashMap.put("Lewis", 29); hashMap.put("Cook", 29); System.out.println("Display entries in HashMap"); System.out.println(hashMap + "\n"); Map<String,Integer> treeMap = new TreeMap<String,Integer>(hashMap); System.out.println("Display entries in ascending order of key"); System.out.println(treeMap); Map<String,Integer> linkedHashMap = new LinkedHashMap<String,Integer>(16,0.75f,true); linkedHashMap.put("Smith", 30); linkedHashMap.put("Anderson",31); linkedHashMap.put("Lewis", 29); linkedHashMap.put("Cook", 29); System.out.println("The age for " + "Lewis is " + linkedHashMap.get("Lewis").intValue()); System.out.println("\nDisplay entries in LinkedHashMap"); System.out.println(linkedHashMap); } }