[八]java作業

數組包裝成list

import java.util.*;

public class test {

	public static void main(String[] args) throws Exception {
		List<Integer> list=Arrays.asList(1,2,3,4,5,6,7,8,9);
		try{
		list.add(10);
		}catch(Exception e){
			System.out.printf("can not add\n");
		}
		finally{
		}
		try{
			list.remove(9);
		}catch(Exception e){
			System.out.printf("can not remove\n");
		}
		finally{
		}
		List<Integer> list2=new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9));
		list2.add(10);
		list2.remove(9);
	}

}
/*
output:
can not add
can not remove
*/

List、map嵌入list 、map 遍歷

import java.util.*;

public class test2 {
	public void mapInList(){
		List<Map> listmap = new ArrayList<Map>();
		Map<Integer, String> map = new HashMap<Integer, String>();
		Map<Integer, Integer> map2 = new HashMap<Integer, Integer>(); 
		
		map.put(1, "aa");
		map.put(2, "bb");
		map.put(3, "cc");
		
		map2.put(1, 1001);
		map2.put(2, 1002);
		map2.put(3, 1003);
		
		listmap.add(map);
		listmap.add(map2);
		
		System.out.printf("map in list:\n");
		for (Map m : listmap) {  
			Iterator<Map.Entry<Object, Object>> it = m.entrySet().iterator();  
			while (it.hasNext()) {  
				Map.Entry<Object, Object> entry = it.next();  
				System.out.print("["+entry.getKey() + " " + entry.getValue()+"] ");  
			}
			System.out.printf("\n");
		}
	}
	public void listInMap(){
		Map<Integer,List<String>> maplist=new HashMap<Integer,List<String>>();
		List<String> tmp=new ArrayList<String>();
		List<String> tmp2=new ArrayList<String>();
		tmp.add("a");
		tmp.add("bb");
		tmp.add("ccc");
		
		tmp2.add("ddd");
		tmp2.add("ee");
		tmp2.add("f");
		
		maplist.put(1, tmp);
		maplist.put(2, tmp2);
		
		System.out.printf("list in map:\n");
		for(Map.Entry<Integer, List<String>> entry:maplist.entrySet()){   
		     System.out.print(entry.getKey()+"=> {"); 
		     for (String m : entry.getValue()) 
						System.out.print("["+m+"] ");
		     System.out.printf("}\n");
		} 
	}
	public static void main(String[] args) {
		test2 tmp=new test2();
		tmp.mapInList();
		tmp.listInMap();
	}

}
/*output
map in list:
[1 aa] [2 bb] [3 cc] 
[1 1001] [2 1002] [3 1003] 
list in map:
1=> {[a] [bb] [ccc] }
2=> {[ddd] [ee] [f] }
 */

Map key值覆蓋

import java.util.*;

public class test3 {

	public static void main(String[] args) {
		Map<Integer,String> map=new HashMap<Integer,String>();

		map.put(1, "aa");
		map.put(2, "bb");
		map.put(3, "cc");
		map.put(2, "dd");
		
		for(Map.Entry<Integer, String> entry:map.entrySet()){   
		     System.out.print(entry.getKey()+"=> ["+entry.getValue()+"]\n"); 
		} 
	}
}
/*
output
1=> [aa]
2=> [dd]
3=> [cc]
*/

泛型編程

參考文章:http://www.cnblogs.com/lwbqqyumidi/p/3837629.html

Sort list排序

import java.util.*;

class student implements Comparable<student>{
    private int id;
    private double result;
    public student(int id,double result){
        this.id=id;
        this.result=result;
    }
    @Override
    public int compareTo(student obj) {
        if(this.result!=obj.result)
            return (int)(obj.result-this.result);
        return this.id-obj.id;
    }
    public String toString(){
        return "["+id+":"+result+"]";
        
    }
}

public class test4 {
    public static void main(String[] args) {
        List<student> tmp=new ArrayList<student>();
        for(int i=0;i<20;i++){
            tmp.add(new student(i+1000,(int)(Math.random()*15)));
        }
        Collections.sort(tmp);
        for (student index : tmp) {
            System.out.println(index);
        }
    }
}
/*
output
[1017:14.0]
[1003:13.0]
[1019:13.0]
[1008:12.0]
[1009:12.0]
[1001:11.0]
[1014:8.0]
[1011:7.0]
[1012:7.0]
[1013:7.0]
[1015:7.0]
[1002:6.0]
[1005:6.0]
[1007:6.0]
[1000:5.0]
[1004:5.0]
[1010:4.0]
[1016:4.0]
[1018:3.0]
[1006:0.0]
*/

文件讀寫

import java.util.*;
import java.io.*;

public class test5 {

	public static void main(String[] args) {
		try{
		BufferedWriter fileBuf = new BufferedWriter(new FileWriter("C:\\Users\\wk950\\Desktop\\test5.txt"));
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		for(String str;;){
			str = buf.readLine();
			fileBuf.write(str);
			fileBuf.newLine();
			if(str.equals(""))break;
		}
		buf.close();
		fileBuf.close();
		}catch(IOException e){
			System.out.printf("error");
		}
	}

}

比較字符串string stringbuffer StringBuilder

public class test6 {
	public void testString(int loopNum){
		String teststr=new String();
		long start=System.currentTimeMillis();
		for(int i=0;i<loopNum;i++){
			teststr+="a";
		}
		long end=System.currentTimeMillis();
		System.out.printf("String        Total Time: %10d\n",end-start);
	}
	public void testStringbuffer(int loopNum){
		StringBuffer teststr=new StringBuffer();
		long start=System.currentTimeMillis();
		for(int i=0;i<loopNum;i++){
			teststr.append("a");
		}
		long end=System.currentTimeMillis();
		System.out.printf("Stringbuffer  Total Time: %10d\n",end-start);
	}
	public void testStringBuilder(int loopNum){
		StringBuilder teststr=new StringBuilder();
		long start=System.currentTimeMillis();
		for(int i=0;i<loopNum;i++){
			teststr.append("a");
		}
		long end=System.currentTimeMillis();
		System.out.printf("StringBuilder Total Time: %10d\n",end-start);
	}
	public static void main(String[] args) {
		test6 tmp=new test6();
		int num=100000;
		tmp.testString(num);
		tmp.testStringbuffer(num);
		tmp.testStringBuilder(num);
	}
}
/*
output
String        Total Time:       4393
Stringbuffer  Total Time:          7
StringBuilder Total Time:          5
*/

實現遞歸展示文件夾

import java.io.*;

public class test7 {
    private static int[] dirlist=new int[255];
    public static void main(String[] args) {
        File dir=new File("C:\\Users\\wk950\\Desktop\\001");
        getAllFiles(dir,0);
    }
    public static void getLevel(int level,int flage)
    {
        for(int l=0;l<level-1;l++)
        {
            if(dirlist[l]==0)
                System.out.printf("│   ");
            else System.out.printf("    ");
        }
        if(flage>1){
            System.out.printf("├───");
            dirlist[level-1]=0;
        }
        else{
            System.out.printf("└───");
            dirlist[level-1]=1;
        }
    }
    public static void getAllFiles(File dir,int level)
    {
        File[] files=dir.listFiles();

        for(int i=0;i<files.length;i++)
        {
            if(files[i].isDirectory())
            {
                getLevel(level+1,files.length-i);
                System.out.println(files[i].getName());
                getAllFiles(files[i],level+1);
            }
            else
            {
                getLevel(level+1,files.length-i);
                System.out.println(files[i].getName());
            }
        }
        
    }
}
/*
├───.classpath
├───.project
├───.settings
│   └───org.eclipse.jdt.core.prefs
├───.vs
│   └───001
│       └───v14
│           └───.suo
├───001
│   ├───bin
│   │   ├───Debug
│   │   │   ├───001.exe
│   │   └───Release
│   ├───Form1.Designer.vb
│   ├───Form1.resx
│   ├───Form1.vb
│   ├───My Project
│   │   ├───Application.Designer.vb
│   │   ├───Application.myapp
│   └───obj
│       └───Debug
│           ├───001.exe
│           ├───001.pdb
│           ├───TempPE
│           │   └───My Project.Resources.Designer.vb.dll
│           ├───_001.Form1.resources
├───001.sln
├───bin
│   ├───adapter.class
│   ├───collectiontest
│   │   ├───collectiontest.class
│   ├───gui
│   │   ├───test1$1.class
│   ├───listtest
│   │   ├───student.class
│   │   ├───test.class
│   ├───number.class
│   ├───show
│   ├───teststatic
│   │   └───testStatic.java
│   └───throwstest
│       └───throwstest.java
└───test5.txt
*/


計算日期之差

import java.text.*;
import java.util.*;

public class test8 {

	public static void main(String[] args) {
		Date date = new Date();
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String dateString = formatter.format(date);
	    System.out.println(dateString);
	}
}
/*
output
2016-11-06 17:12:34
*/


發佈了23 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章