1. 程式人生 > 其它 >JAVA---泛型與File

JAVA---泛型與File

package exer;

/**
 *
 * @create 2022-04-08 16:40
 */
public class MyDate implements Comparable<MyDate>{
    private int year;
    private int month;
    private int day;

    public MyDate() {
    }

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }


    @Override
    public int compareTo(MyDate o) {
        int minusYear=this.getYear()-o.getYear();
        if(minusYear!=0){
            return minusYear;
        }
        int minusMonth=this.getMonth()-o.getMonth();
        if(minusMonth!=0){
            return minusMonth;
        }
        return this.getDay()-o.getDay();
    }
}
package exer;

/**
 *
 *
 *
 * @create 2022-04-08 16:46
 */
public class Employee implements Comparable<Employee>{

    private String name;
    private int age;
    private MyDate birthday;

    public Employee() {
    }

    public Employee(String name, int age, MyDate birthday) {

        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "exer.Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    @Override
    public int compareTo(Employee o) {
        return this.name.compareTo(o.name);
    }
}
package exer;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 *
 *
 * @create 2022-04-08 17:00
 */
public class EmployeeTest {

    @Test
    public void test2(){
        TreeSet<Employee> set=new TreeSet<>(new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                MyDate b1=o1.getBirthday();
                MyDate b2=o2.getBirthday();

                return b1.compareTo(b2);

            }
        });
        Employee e1 = new Employee("liudehua",55,new MyDate(1965,5,4));
        Employee e2 = new Employee("zhangxueyou",43,new MyDate(1987,5,4));
        Employee e3 = new Employee("guofucheng",44,new MyDate(1987,5,9));
        Employee e4 = new Employee("liming",51,new MyDate(1954,8,12));
        Employee e5 = new Employee("liangzhaowei",21,new MyDate(1978,12,4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator<Employee> iterator=set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test1(){
        TreeSet<Employee> set=new TreeSet<>();
        Employee e1 = new Employee("liudehua",55,new MyDate(1965,5,4));
        Employee e2 = new Employee("zhangxueyou",43,new MyDate(1987,5,4));
        Employee e3 = new Employee("guofucheng",44,new MyDate(1987,5,9));
        Employee e4 = new Employee("liming",51,new MyDate(1954,8,12));
        Employee e5 = new Employee("liangzhaowei",21,new MyDate(1978,12,4));


        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator<Employee> iterator=set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

package java0;

import org.junit.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 *
 *
 * @create 2022-04-08 17:36
 */
public class GenericTest {
    @Test
    public void test1(){
        Map<String,Integer> map=new HashMap<>();

        map.put("Tom",87);
        map.put("Jerry",87);
        map.put("Jack",67);
        Set<Map.Entry<String, Integer>> entries = map.entrySet();

        Iterator<Map.Entry<String, Integer>> iterator = entries.iterator();

        while(iterator.hasNext()){
            Map.Entry<String, Integer> e = iterator.next();
            String key=e.getKey();
            Integer value=e.getValue();
            System.out.println(key+"----->"+value);
        }

    }
}
package java0;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @create 2022-04-08 17:51
 */
public class GenericTest1 {

    @Test
    public void test1(){
        //如果定義了泛型類,例項化沒有指明類的泛型,則認為此泛型型別為Object型別。
        Order order=new Order();
        order.setOrderT(123);
        order.setOrderT("ABC");

        Order<String> order1=new Order<>("orderAA",1001,"order:AA");
        order1.setOrderT("AA:hello");

    }


    /*
        子類不保留父類的泛型:
        1)沒有型別
            class Son extends Father{}
            等價於 class Son extends Father<Object,Object>{}
        2)具體型別
            class Son extends Father<Integer,String>{}
        子類保留父類的泛型:
        1)全部保留
            class Son<T1,T2> extends Father<T1,T2>{}
        2)部分保留
            class Son<T2> extends Father<Integer,T2>{}


        子類不保留父類的泛型
        1)沒有型別
            class Son<A,B> extends Father{}
            等價於class Son extends Father<Object,Object>{}
        2)具體型別
            class Son<A,B> extends Father<Integer,String>{}
        子類保留父類的泛型
        1)全部保留
            class Son<T1,T2,A,B> extends Father<T1,T2>{}
        2)部分保留
            class Son<T2,A,B> extends Father<Integer,T2>{}




     */
    @Test
    public void test2(){
        SubOrder sub1=new SubOrder();

        sub1.setOrderT(1111);

        SubOrder1<Integer> sub2=new SubOrder1<>();
        sub2.setOrderT(12312);

    }
    @Test
    public void test3(){
        ArrayList<String> list1=null;
        ArrayList<Integer> list2=new ArrayList<>();
        //泛型不同的引用不能相互賦值
//        list1=list2;會報錯

    }

    @Test
    public void test4(){
        Order<String> order=new Order<>();
        Integer[] arr=new Integer[]{1,2,3,4};
        List<Integer> list=order.copy(arr);
        System.out.println(list);
    }
}
package java0;

/**
 *
 *
 * @create 2022-04-08 18:45
 */
public class SubOrder1<T> extends Order<T> {
    //SubOrder1是泛型類


}
package java0;

/**
 *
 *
 * @create 2022-04-08 18:40
 */
public class SubOrder extends Order<Integer> {//SubOrder:不是泛型類


}
package java0;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 自定義泛型類
 * @create 2022-04-08 17:54
 */
public class Order<T> {
    String orderName;
    int orderId;
    T orderT;

    public Order(){
        T[] arr=(T[]) new Object[10];

    }

    public Order(String orderName,int orderId,T orderT){
        this.orderName=orderName;
        this.orderId=orderId;
        this.orderT=orderT;
    }

    public T getOrderT(){
        return orderT;
    }
    public void setOrderT(T orderT){
        this.orderT=orderT;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderName='" + orderName + '\'' +
                ", orderId=" + orderId +
                ", orderT=" + orderT +
                '}';
    }

    //靜態方法中不能使用類的泛型,原因:類的生命週期

    //泛型方法:在方法中出現了泛型的結構,泛型引數與類的泛型引數沒有任何關係。
    //泛型方法:可以宣告為靜態的。s

    public static <E> List<E> copy(E[] arr){
        ArrayList<E> list=new ArrayList<>();

        for(E e:arr){
            list.add(e);
        }
        return list;
    }
}

package java2;

import org.junit.Test;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @create 2022-04-10 12:14
 */
public class GenericTest {

    /*
        泛型在繼承方面的體現
        雖然類A是類B的父類,但是G<A>和G<B>二者不具備子父類關係,二者是並列關係。

        若類A是類B的父類,A<G>是B<G>的父類。

     */
    @Test
    public void test1(){
        Object obj=null;
        Object str=null;
        obj=str;

        Object[] arr1=null;
        String[] arr2=null;
        arr1=arr2;

        List<Object> list1=null;
        List<String> list2=new ArrayList<>();

        //此時的list1和list2的型別不具有子父類關係
//        list1=list2;  //編譯不通過


    }

    @Test
    public void test2(){
        AbstractList<String> list1=null;
        List<String> list2=null;
        ArrayList<String> list3=null;

        list1=list3;
        list2=list3;
        list2=list1;
    }

    /*
        萬用字元的使用:
            萬用字元:?
            類A是類B的父類,G<A> 和G<B>是沒有關係的,二者共同的父類是:G<?>


     */

    @Test
    public void test3(){
        List<Object> list1=null;
        List<String> list2=null;

        List<?> list=null;

        list=list1;
        list=list2;


        List<String> list3=new ArrayList<>();
        list3.add("AA");
        list3.add("BB");
        list3.add("CC");
        list=list3;

        //list<?>不能向其內部新增資料,除了null之外。
//        list.add("DD");   //編譯不通過

        list.add(null);

        //獲取:允許list獲取資料,讀取的資料型別為Object。
        Object o=list.get(0);
        System.out.println(o);


    }

    /*
        有限制條件的萬用字元的使用:
        ? extends A:
            G<? extends A> 可以作為G<A>和G<B>的父類,其中B是A的子類。

        ? super A:
            G<? super A> 可以作為G<A>和G<B>的父類,其中B是A的父類。


     */
    @Test
    public void test4(){
        List<? extends Person> list1=null;
        List<? super Person> list2=null;

        List<Student> list3=new ArrayList<>();
        List<Person> list4=new ArrayList<>();
        List<Object> list5=new ArrayList<>();

        list1=list3;
        list1=list4;
//        list1=list5;//編譯不通過

//        list2=list3;//編譯不通過
        list2=list4;
        list2=list5;

        //讀取資料
        list1=list3;
        Person p=list1.get(0);
        
        list2=list4;
        Object obj=list2.get(0);
        
        //寫入資料
//        list1.add(new Person());//編譯不通過
        
        list2.add(new Person());
        list2.add(new Student());
        

    }

}

package exer1;

/**
 *
 * 定義一個 User 類:
 該類包含:private成員變數(int型別) id,age;(String 型別)name。
 *
 * @create 2022-04-10 18:32
 */
public class User {
    private int id;
    private int age;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User(int id, int age, String name) {

        this.id = id;
        this.age = age;
        this.name = name;
    }

    public User() {

    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != user.id) return false;
        if (age != user.age) return false;
        return name != null ? name.equals(user.name) : user.name == null;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + age;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

}
package exer1;

import java.util.*;

/**
 *
 *定義個泛型類 DAO<T>,在其中定義一個Map 成員變數,Map 的鍵為 String 型別,值為 T 型別。

 分別建立以下方法:
 public void save(String id,T entity): 儲存 T 型別的物件到 Map 成員變數中
 public T get(String id):從 map 中獲取 id 對應的物件
 public void update(String id,T entity):替換 map 中key為id的內容,改為 entity 物件
 public List<T> list():返回 map 中存放的所有 T 物件
 public void delete(String id):刪除指定 id 物件
 * @create 2022-04-10 18:34
 */
public class DAO<T> {
    private HashMap<String,T> map=new HashMap<>();

    //儲存T型別的物件到Map成員變數中
    public void save(String id,T entity){
        map.put(id,entity);
    }
    //從map中獲取id對應的物件
    public T get(String id){
        return map.get(id);
    }
    //替換map中key為id的內容,改為entity物件
    public void update(String id,T entity){
        if(map.containsKey(id)){
            map.put(id,entity);
        }
    }
    //返回map中存放的所有T物件
    public List<T> list(){
        ArrayList<T> list=new ArrayList<>();
        Collection<T> values=map.values();
        for(T t:values){
            list.add(t);
        }
        return list;
    }
    //刪除指定id物件
    public void delete(String id){
        map.remove(id);
    }


}
package exer1;

import java.util.List;

/**
 *
 *
 * @create 2022-04-10 18:45
 */
public class DAOTest {

    public static void main(String[] args) {
        DAO<User> dao=new DAO<>();
        dao.save("1001",new User(1001,999,"太陽騎士"));
        dao.save("1002",new User(1002,444,"帕奇"));
        dao.save("1003",new User(1003,555,"爺"));

        dao.update("1003",new User(1003,111,"朕"));
        dao.delete("1002");

        List<User> list = dao.list();
        list.forEach(System.out::println);
    }
}

package java3;

import org.junit.Test;

import javax.sound.midi.Soundbank;
import java.io.File;
import java.io.IOException;

/**
 *
 *
 * @create 2022-04-10 19:48
 */
public class FileTest {

    /*
        1.如何建立File類的例項
        File(String filePath)
        File(String parentPath,String childPath)
        File(File parentFile,String childPath)

       2.
       相對路徑:相較於某個路徑下,指明的路徑
       絕對路徑:包含碟符在內的檔案或檔案目錄的路徑

       3.路徑分隔符
        windows:\\
        unix:/


     */
    @Test
    public void test1(){
        //構造器1
        File file1=new File("hello.txt");
        File file2=new File("D:\\java\\workspace_idea\\ioTest\\hi.txt");

        System.out.println(file1);
        System.out.println(file2);
    }

    /*
        pubilc String getAbsolutePath():獲取絕對路徑
        public String getPath():獲取路徑
        pubilc String getName():獲取名稱
        public String getParent():獲取上層檔案目錄路徑。若無,返回null
        public long length():獲取檔案長度(即:位元組數)。不能獲取目錄的長度
        public long lastModified():獲取最後一次的修改時間,毫秒值

        適用於檔案目錄的方法:
        public String[] list():獲取指定目錄下的所有檔案或者檔案目錄的名稱(String型別)陣列
        public File[] listFiles():獲取指定目錄下的所有檔案或者檔案目錄的File陣列。

     */
    @Test
    public void test2(){
        File file1=new File("hello.txt");
        File file2=new File("D:\\java\\workspace_idea\\ioTest\\hi.txt");

        System.out.println(file1.getAbsoluteFile());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParent());
        System.out.println(file1.length());
        System.out.println(file1.lastModified());

        System.out.println();

        System.out.println(file2.getAbsoluteFile());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());
        System.out.println(file2.getParent());
        System.out.println(file2.length());
        System.out.println(file2.lastModified());
    }

    @Test
    public void test3(){
        File file=new File("D:\\java\\workspace_idea");

        String[] list=file.list();
        for(String s:list){
            System.out.println(s);
        }
        System.out.println();

        File[] files=file.listFiles();
        for(File f:files){
            System.out.println(f);
        }

    }

    /*
        public boolean renameTo(File dest):把檔案重新命名為指定的檔案路徑
             比如:file1.renameTo(file2)為例
                要想保證返回true,需要file1在硬碟中是存在的,且file2不能在硬碟中存在。
     */
    @Test
    public void test4(){
        File file1=new File("hello.txt");
        File file2=new File("D:\\java\\workspace_idea\\ioTest\\hi.txt");

        boolean renameTo=file2.renameTo(file1);
        System.out.println(renameTo);

    }

    /*
        public boolean isDirectory():判斷是否是檔案目錄
        public boolean isFile():判斷是否是檔案
        public boolean exists():判斷是否存在
        public boolean canRead():判斷是否可讀
        public boolean canWrite():判斷是否可寫
        pubilc boolean isHidden():判斷是否隱藏
     */

    @Test
    public void test5(){
        File file1=new File("hello.txt");
            file1=new File("hello1.txt");
        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());
        System.out.println();

        File file2=new File("D:\\java\\workspace_idea\\ioTest");
            file2=new File("D:\\java\\workspace_idea\\ioTest1");
        System.out.println(file2.isDirectory());
        System.out.println(file2.isFile());
        System.out.println(file2.exists());
        System.out.println(file2.canRead());
        System.out.println(file2.canWrite());
        System.out.println(file2.isHidden());

    }

    /*
        建立硬碟中對應的檔案或檔案目錄
        public boolean createNewFile():建立檔案。若檔案存在,則不建立,返回false.
        public boolean mkdir():建立檔案目錄。如果此檔案目錄存在,就不建立了。如果此檔案目錄的上層目錄不存在,不建立。
        public boolean mkdirs():建立檔案目錄。如果此檔案目錄存在,就不建立了。如果此檔案目錄的上層目錄不存在,一併建立


        刪除磁碟中的檔案或檔案目錄
        public boolean delete():刪除檔案或者資料夾
        刪除注意事項:java中的刪除不走回收站。

     */
    @Test
    public void test6() throws IOException {
        File file1=new File("hi.txt");
        if(!file1.exists()){
            file1.createNewFile();
            System.out.println("建立成功!");
        }else{
            file1.delete();
            System.out.println("刪除成功");
        }
    }

    @Test
    public void test7(){
        //檔案目錄的建立
        File file1=new File("D:\\java\\workspace_idea\\ioTest1\\222");
        boolean mkdir=file1.mkdir();
        if(mkdir){
            System.out.println("建立成功1");
        }

        File file2=new File("D:\\java\\workspace_idea\\ioTest1\\222");
        boolean mkdir2=file2.mkdirs();
        if(mkdir2){
            System.out.println("建立成功2");
        }

        //刪除檔案
        File file3=new File("D:\\java\\workspace_idea\\ioTest1\\222");
        System.out.println(file3.delete());
    }


}