• JDK中的泛型


    Java中的泛型介绍:

      起因:

        1. JDK 1.4 以前类型不明确:

          ① 装入集合的对象被当作 Object 类型对待,从而失去了自己的原有类型;

                   ② 从集合中取出时往往需要转型,效率低下,并且容易产生错误.

          解决办法:

               2. 解决办法

          ① 在定义集合的时候,同时定义集合中对象的类型;

                   ② 可以在定义 Collection 的时候指定,也可以在循环时用 Iterator 指定.

          好处:

        3. 增强程序的可读性与稳定性.

    Demo_1:

    import java.util.*;
    class MyName implements Comparable<MyName>{
    	private int age;
    	public MyName(int age) {
    		this.age = age;
    	}
    
    	@Override
    	public int compareTo(MyName mn) {
    		if(this.age>mn.age){
    			return 1;
    		}else if(this.age<mn.age){
    			return -1;
    		}else {
    			return 0;
    		}
    	}
    }
    public class Test {
    	public static void main(String[] args) {
    		ArrayList<String> as = new ArrayList<String>();
    		as.add("aa");
    		as.add("bb");
    		as.add("cc");
    		as.add("dd");
    		for(int i=0;i<as.size();i++){
    			String sa = as.get(i);
    			System.out.print(sa+"  "); // 输出:aa  bb  cc  dd  
    		}
    		System.out.println();
    		HashSet<String> hs = new HashSet<String>();
    		hs.add("a1");
    		hs.add("a2");
    		hs.add("a3");
    		hs.add("a4");
    		hs.add("a5");
    		for(Iterator<String> it=hs.iterator();it.hasNext();){
    			String sh = it.next();
    			System.out.print(sh+"  "); // 输出:a1  a2  a3  a4  a5  
    		}
    		System.out.println();
    		MyName m1 = new MyName(12);
    		MyName m2 = new MyName(25);
    		System.out.println(m1.compareTo(m2)); // 输出:-1
    	}
    }
    

    Demo_2:

    import java.util.*;
    public class Test {
    	public static void main(String[] args) {
    		HashMap<String, Double> mp = new HashMap<String, Double>();
    		mp.put("one", 112.365);
    		mp.put("two", 2.458);
    		mp.put("three", 126.258);
    		System.out.println(mp.size()); // 输出:3
    		System.out.println(mp.containsKey("two")); // 输出:true
    		if(mp.containsKey("three")){
    			Double i = mp.get("three"); // get Value
    			System.out.println(i); // 输出:126.258
    		}
    	}
    }
    

      

           

  • 相关阅读:
    Problem C: 时间类的常量
    Problem B: 时间类的错误数据处理
    Problem A: 时间类的拷贝和整体读写
    Problem B: 平面上的点——Point类 (IV)
    Problem C: 平面上的点——Point类 (V)
    Problem A: 平面上的点——Point类 (III)
    中间的数(若已经排好序)
    软件工程概论团队结组
    软件工程个人作业04 子数组循环数组
    软件工程个人作业03
  • 原文地址:https://www.cnblogs.com/bosongokay/p/6769146.html
Copyright © 2020-2023  润新知