《java语言程序设计》初步学习——各种小Demo

      发现现在的天下几乎都是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");
        }
    }

}
View Code

 

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 }
View Code

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)");
    }
}
View Code

数据和方法的可见性

类中成员的修饰符 在同一类内访问 在同一包内访问 在子类内可访问 在不同包可访问
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() + " ");
        }

    }

}
View Code

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

}
View Code

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

}
View Code

 

三.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() + "  ");
        }
    }

}
View Code

 

四.向量类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);
    }
}
View Code

 

posted @ 2014-03-22 21:09  中大黑熊  阅读(9436)  评论(1编辑  收藏  举报