19 programming that must be mastered in Java se Foundation

Posted by morris520 on Sat, 04 Jan 2020 18:10:30 +0100

1. Reverse order of array

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. Array search

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

3. Traversal of array

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. the maximum value of the array

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) {
    //Add to ArrayList in, utilize lambda Expression get maximum
    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) {
    //utilizeCollectionPrioritize,Then print
    ArrayList<Integer> list = new ArrayList<Integer>();
    for(int i=0;i<arr.length;i++) {
        list.add(arr[i]);
    }
    Collections.sort(list);//Default ascending sort
    System.out.println("max: "+list.get(list.size()-1)+",min: "+list.get(0));
}

5. Bubble sorting

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. Select Sorting

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. Binary search

//Binary search presupposes that the array is ordered, so you need to sort the array at first
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]) {//Determine whether the array is in ascending or descending order
            if(num==middle) {
                System.out.println(num+"The index in the array is:"+middleIndex);
                return;
            }else if(num>middle) {
                start=middleIndex+1;
            }else {
                end=middleIndex-1;
            }
        }else {
            if(num==middle) {
                System.out.println(num+"The index in the array is:"+middleIndex);
                return;
            }else if(num>middle) {
                end=middleIndex-1;
            }else {
                start=middleIndex+1;
            }
        }
    }
    System.out.println("I'm sorry,The number does not exist in the array");
}

8. Writing method of single design pattern

//Hungry man
class Hungry{
    private static Hungry h=new Hungry();
    private Hungry() {      
    }
    public static Hungry getInstance() {
        return h;
    }
}
//Slacker type
class Lazy{
    private static Lazy l=null;
    private Lazy() {        
    }
    public static Lazy getInstance() {
        if(l==null) {
            l=new Lazy();
        }
        return l;
    }   
}

9. Recursively find files

public void searchFiles(String path,String suffix) {
    //Wrap the path as a File class
    File file = new File(path);
    //Judge folder or file
    if(file.isFile()&&(file.getAbsolutePath().toLowerCase().endsWith(suffix)) ) {//If it's a file
        System.out.println(file.getAbsolutePath());

    }else {//If it's a folder, get its contents
        File[] files = file.listFiles();
        if(files!=null&&files.length>0) {
            for (File f : files) {//After traversing the content, call the method recursively
                searchFiles(f.getAbsolutePath(), suffix);
            }
        }
    }
}

10. Delete files recursively

public void deleteFiles(String path) {
    /**
     * Delete the file. There is content in the folder in java. You cannot delete the folder. An empty folder is the file
     */
    //Wrap the path into a class, judge whether it is a folder, and then delete
    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();//Then delete yourself
    }
}

11.Map traversal

public void mapBianli(Map<Integer,String> map) {
     Set<Entry<Integer, String>> entrySet = map.entrySet();
     Iterator<Entry<Integer, String>> iterator = entrySet.iterator();
     //Using Iterators 
     while(iterator.hasNext()) {
         Entry<Integer, String> next = iterator.next();
         System.out.println(next.getKey()+next.getValue());
     }
    //Use enhanced for loop
     for (Entry<Integer, String> entry : entrySet) {
        System.out.println(entry.getKey()+entry.getValue()); 
    }
    //Printing with keySet
    Set keySet = map.keySet();
    for (Object key : keySet) {
        System.out.println("key:"+key +", value"+map.get(key));
    }
}

12. Iterator is used to traverse the collection

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

13. How to call member variables and static variables
*Member variable called with object name
*Static variable called with class name

14. How to define an interface and implement

public interface A{
    public void show();
}
public class SubInstance implements A{
    public void show(){
        System.out.println("Gourd doll,Gourd doll,Seven melons on one vine")
    }
}

15. The writing method of anonymous inner class

Anonymous inner class refers to the implementation of an interface,Or inherited one(abstract) Subclass object of class;
//Format:
    new Interface/(abstract)Class name ( ){Rewrite method};
    new A(){
        public void eat(){
            sysout("Where is the elixir of immortality?")
        }
    }.eat();
    //Or:
    A a=new A(){
        public void eat(){
            sysout("Where is the elixir of immortality?")
    };
--------------
new A() {
    public void show() {
        System.out.println("I'm a newspaper salesman");
    }
}.show();

A a=new A() {

    @Override
    public void show() {
        System.out.println("I'm the second way to write anonymous inner classes ");
    }

};

16. Use Comparable and Comparator to sort the Person classes respectively (rules are self-determined)

public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person("Gourd doll",10,95));
        list.add(new Person("Nezha",5,96));
        list.add(new Person("Iron courage Trainman",5,93));
        list.add(new Person("Master Chang Ji",9,99));

        /**
         * Using Comparable to sort the Person class requires the Person class to implement the comparator < generic Person type > interface
         * Then the method is rewritten and designed according to the implementation mode
         */
        Collections.sort(list,new  Person());
        for (Person person : list) {
            System.out.println(person);
        }
        ---------------------------------------------
        /**
         * Using Comparator to sort person class
         * Anonymous inner class using interface, (list, new comparator < person > () {method override});
         */
        Collections.sort(list, new Comparator<Person>() {

            @Override
            public int compare(Person o1, Person o2) {
                //Rank in ascending order of age. If the ages are the same, the scores will be ranked in ascending order
                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());
        }
        ---------------------------------------------   
        //Using lambda expressions
        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. Transmission of UDP data

    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("Peaks and peaks gather.,The waves are fury.,Tongguan Road".getBytes(),
                "Peaks and peaks gather.,The waves are fury.,Tongguan Road".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 establishes connection and transmits data (multi-layer folder)

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("Connected");
        BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:/users/gaopu/desktop/Copy copy.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("Received");
        s.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}       

}

19. Multi thread ticket buying program

Thread thread1 = new Thread(new Tickets(),"Window 1" );  
Thread thread2 = new Thread(new Tickets(),"Window 2" );  
Thread thread3 = new Thread(new Tickets(),"Window 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("The first"+Thread.currentThread().getName()+
                    "Windows selling"+ tickets-- +"Zhang ticket");
        }else {
            break;
        }
        lock.unlock();
    }

    }

Topics: socket Lambda Java Windows