1. 程式人生 > >Javase 基礎中必須要掌握的19個程式設計

Javase 基礎中必須要掌握的19個程式設計

1.陣列的逆序

public void getReverse1(int[]arr) {
    int start=0;
    int end=arr.length-1;
    for(int i=0;i<arr.length/2;i++) {
            int temp=arr[start];
            arr[start]=arr[end];
            arr[end]=temp;
            start++;
            end--;
        }
    }
public void getReverse2(int
[]arr) { for(int start=0,end=arr.length-1;start<end;start++,end--) { int temp=arr[start]; arr[start]=arr[end]; arr[end]=temp; }

2.陣列的查詢

public int search(int[]arr,int num) {
    for(int i=0;i<arr.length;i++) {
        if(num==arr[i]) {
            return i;
        }
    }
    return
-1;

3.陣列的遍歷

public void printArr1(int [] arr) {
    for (int i : arr) {
        System.out.println(i);
    }
}
public void printArr2(int[] arr) {
    for(int i=0;i<arr.length;i++) {
        System.out.println(arr[i]);
    }
}

4.陣列的最值

public void getMaxandMin0(int [] arr) {
    int max=arr[0
]; for(int i=0;i<arr.length;i++) { if(arr[i]>max) { max=arr[i]; } } int min=arr[0]; for(int i=0;i<arr.length;i++) { if(arr[i]<min) { min=arr[i]; } } System.out.println("max: "+max+",min: "+min); } public void getMaxandMin1(int [] arr) { //新增到ArrayList 中, 利用lambda表示式獲取最值 ArrayList<Integer> list = new ArrayList<Integer>(); for(int i=0;i<arr.length;i++) { list.add(arr[i]); } Integer max = list.stream().reduce((a,b)->(a>b?a:b)).get(); Integer min = list.stream().reduce((a,b)->(a<b?a:b)).get(); System.out.println("max: "+max+",min: "+min); } public void getMaxandMin2(int [] arr) { //利用Collection先排序,然後列印 ArrayList<Integer> list = new ArrayList<Integer>(); for(int i=0;i<arr.length;i++) { list.add(arr[i]); } Collections.sort(list);//預設升序排序 System.out.println("max: "+list.get(list.size()-1)+",min: "+list.get(0)); }

5.氣泡排序

public void bubbleSort(int[] arr) {
        for(int i=0;i<arr.length-1;i++) {
            for(int j=0;j<arr.length-1-i;j++) {
                if(arr[j]>arr[j+1]) {
                    int temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }

6.選擇排序

public void selecSort(int [] arr) {
    for(int i=0;i<arr.length-1;i++) {
        for(int j=i+1;j<arr.length;j++) {
            if(arr[i]>arr[j]) {
                int temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
    System.out.println(Arrays.toString(arr));
}

7.二分查詢

//二分查詢前提是陣列是有序的,所以開始需要對陣列進行排序
public void binarySearch(int[] arr,int num) {
    int start=0;
    int end=arr.length-1;
    while(start<=end) {
        int middleIndex=(start+end)/2;
        int middle=arr[middleIndex];
        if(arr[0]<arr[arr.length-1]) {//判斷陣列為升序還是降序
            if(num==middle) {
                System.out.println(num+"所在陣列中的索引是:"+middleIndex);
                return;
            }else if(num>middle) {
                start=middleIndex+1;
            }else {
                end=middleIndex-1;
            }
        }else {
            if(num==middle) {
                System.out.println(num+"所在陣列中的索引是:"+middleIndex);
                return;
            }else if(num>middle) {
                end=middleIndex-1;
            }else {
                start=middleIndex+1;
            }
        }
    }
    System.out.println("對不起,陣列中不存在該數");
}

8.單例設計模式的寫法

//餓漢式
class Hungry{
    private static Hungry h=new Hungry();
    private Hungry() {      
    }
    public static Hungry getInstance() {
        return h;
    }
}
//懶漢式
class Lazy{
    private static Lazy l=null;
    private Lazy() {        
    }
    public static Lazy getInstance() {
        if(l==null) {
            l=new Lazy();
        }
        return l;
    }   
}

9.遞迴查詢檔案

public void searchFiles(String path,String suffix) {
    //將路徑包裝成File類
    File file = new File(path);
    //判斷資料夾或檔案
    if(file.isFile()&&(file.getAbsolutePath().toLowerCase().endsWith(suffix)) ) {//如果是檔案
        System.out.println(file.getAbsolutePath());

    }else {//如果是資料夾,獲取其內容
        File[] files = file.listFiles();
        if(files!=null&&files.length>0) {
            for (File f : files) {//遍歷內容後 , 遞迴呼叫方法
                searchFiles(f.getAbsolutePath(), suffix);
            }
        }
    }
}

10.遞迴刪除檔案

public void deleteFiles(String path) {
    /**
     * 刪除檔案, java中資料夾裡有內容,無法刪除該資料夾, 空資料夾就是檔案
     */
    //將路徑包裝成類, 然後判斷是否為資料夾,然後刪除
    File file = new File(path);
    if(file.isFile()) {
        file.delete();
    }else {
        File[] files = file.listFiles();
        if(files!=null&&files.length>0) {
            for (File f : files) {
                deleteFiles(f.getAbsolutePath());

            }
        }
        file.delete();//之後把自己刪除
    }
}

11.Map的遍歷

public void mapBianli(Map<Integer,String> map) {
     Set<Entry<Integer, String>> entrySet = map.entrySet();
     Iterator<Entry<Integer, String>> iterator = entrySet.iterator();
     //使用迭代器
     while(iterator.hasNext()) {
         Entry<Integer, String> next = iterator.next();
         System.out.println(next.getKey()+next.getValue());
     }
    //使用增強for迴圈
     for (Entry<Integer, String> entry : entrySet) {
        System.out.println(entry.getKey()+entry.getValue()); 
    }
    //利用keySet列印
    Set keySet = map.keySet();
    for (Object key : keySet) {
        System.out.println("key:"+key +", value"+map.get(key));
    }
}

12.使用迭代器完成對集合的遍歷

public void iteratorList(List list) {
    Iterator it = list.iterator();
    while(it.hasNext()) {
        System.out.println(it.next());
    }
}

13.如何呼叫成員變數和靜態變數
* 成員變數使用物件名呼叫
* 靜態變數使用類名呼叫

14.如何實現定義一個介面,並實現

public interface A{
    public void show();
}
public class SubInstance implements A{
    public void show(){
        System.out.println("葫蘆娃,葫蘆娃,一根藤上七個瓜")
    }
}

15.匿名內部類的寫法

匿名內部類指的是  實現了一個介面,或是繼承了一個(抽象) 類的 子類物件;
格式:
    new 介面/(抽象)類名 ( ){重新寫的方法};
    new A(){
        public void eat(){
            sysout("長生不老藥何在?")
        }
    }.eat();
    或者:
    A a=new A(){
        public void eat(){
            sysout("長生不老藥何在?")
    };
--------------
new A() {
    public void show() {
        System.out.println("我是賣報的小行家");
    }
}.show();

A a=new A() {

    @Override
    public void show() {
        System.out.println("我是匿名內部類的第二種書寫方式 ");
    }

};

16.分別使用Comparable和Comparator實現對Person類的排序(規則自定)

public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person("葫蘆娃",10,95));
        list.add(new Person("哪吒",5,96));
        list.add(new Person("鐵膽火車俠",5,93));
        list.add(new Person("藤吉少爺",9,99));

        /**
         * 使用 Comparable 對Person類進行排序 ,需要Person 類實現 Comparator<泛型 Person型別> 介面
         * 然後 方法重寫, 按照實現 方式進行設計
         */
        Collections.sort(list,new  Person());
        for (Person person : list) {
            System.out.println(person);
        }
        ---------------------------------------------
        /**
         * 使用 Comparator 實現對person類的排序
         * 使用介面的匿名內部類,(list,new Comparator<Person>() {方法重寫});
         */
        Collections.sort(list, new Comparator<Person>() {

            @Override
            public int compare(Person o1, Person o2) {
                //年齡升序排列,如果年齡相同,那麼成績將序排列
                if(o1.getAge()==o2.getAge()) {
                    return o2.getScore()>o1.getScore()?1:-1;
                }
                return o1.getAge()-o2.getAge();
            }
        });
        Iterator<Person> it = list.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
        ---------------------------------------------   
        //使用lambda表示式
        Collections.sort(list, (o1,o2)->{
            if(o1.getAge()==o2.getAge()) {
                return o2.getScore()>o1.getScore()?1:-1;
            }
            return o1.getAge()-o2.getAge();
        });
        Iterator<Person> it2 = list.iterator();
        while(it2.hasNext()) {
            System.out.println(it2.next());
        }

17.UDP資料的傳輸

    Thread thread = new Thread(client);
    Thread thread2 = new Thread(server);
    thread2.start();
    Thread.sleep(200);
    thread.start();
    ------------------------
    new Thread(new Server()).start();
    Thread.sleep(200);
    new Thread(new Client()).start();


    class Client implements Runnable{
@Override
public void run() {
    try {
        DatagramSocket ds=new DatagramSocket();
        DatagramPacket dp = new DatagramPacket("峰巒如聚,波濤如怒,山河表裡潼關路".getBytes(),
                "峰巒如聚,波濤如怒,山河表裡潼關路".getBytes().length , InetAddress.getLocalHost(), 8686);
        ds.send(dp);
        ds.close();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }           
}
}
class Server implements Runnable{


public void run() {
    try {
        DatagramSocket ds=new DatagramSocket(8686);

        DatagramPacket dp = new DatagramPacket(new byte[64*1024],64*1024);
        ds.receive(dp);
        byte[] data = dp.getData();
        int length = dp.getLength();
        InetAddress address = dp.getAddress();
        System.out.println(address.getHostAddress()+"+++"+new String(data,0,length));
        ds.close();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}       
}

18.TCP建立連線並傳輸資料(多層資料夾)

class TcpClient implements Runnable{
        public void run() {
        try {
            Socket s= new Socket("127.0.0.1", 1991);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:/users/gaopu/desktop/P70621-081006-1.png"));
            BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
            byte[] bs=new byte[1024];
            int len;
            while((len=bis.read(bs))!=-1) {
                bos.write(bs,0,len);
            }
            bos.flush();
            bos.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class TcpServer implements Runnable{
public void run() {
    try {
        ServerSocket ss= new ServerSocket(1991);
        Socket s = ss.accept();
        System.out.println("已連線");
        BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:/users/gaopu/desktop/拷貝副本.png"));
        byte[] bs=new byte[1024];
        int len;
        while((len=bis.read(bs))!=-1) {
            bos.write(bs,0,len);
        }
        bos.flush();
        bos.close();
        System.out.println("已接收");
        s.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}       

}

19.多執行緒買票程式

Thread thread1 = new Thread(new Tickets(),"視窗1" );  
Thread thread2 = new Thread(new Tickets(),"視窗2" );  
Thread thread3 = new Thread(new Tickets(),"視窗3" );  
thread1.start();    
thread2.start();    
thread3.start();    

class Tickets implements Runnable{
    static int tickets=100;

public  void run() {
     ReentrantLock lock = new ReentrantLock();
        while(true) {
        lock.lock();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(tickets>0) {
            System.out.println("第"+Thread.currentThread().getName()+
                    "個視窗正在售第"+ tickets-- +"張票");
        }else {
            break;
        }
        lock.unlock();
    }

    }