JAVA 범례 14) 범 형

19656 단어 자바
제1 4 장 범 형
14.1 범 형 기초
실례 255 범 형 에 대한 간단 한 예
import java.util.Date;

public class MyFirstGeneric<T> {
	T t; //t    T,            ,            

	MyFirstGeneric(T t) {//           T    
		this.t = t;
	}

	//            T
	T getT() {
		return t;
	}

	//   T   
	void printType() {
		System.out.println("Type of T is:" + t.getClass().getName());
	}

	public static void main(String args[]) {
		//     String   Generic  
		MyFirstGeneric<String> str;
		//     String   Generic  
		str = new MyFirstGeneric<String>("           ");
		//         
		str.printType();
		String string = str.getT();
		System.out.println("\tstring=" + string);
		//     Date   Generic  
		MyFirstGeneric<Date> sobj;
		//     Date   Generic  
		sobj = new MyFirstGeneric<Date>(new Date());
		//         
		sobj.printType();
		String time = sobj.getT().toGMTString();
		System.out.println("\ttime=" + time);
	}

}

 
인 스 턴 스 256 두 가지 유형의 매개 변 수 를 가 진 범 형
public class MoreParameters<T, V> {
	T t;

	V v;

	//                 
	MoreParameters(T t1, V v1) {
		t = t1;
		v = v1;
	}

	//   T V   
	void printTypes() {
		System.out.println("  T      : " + t.getClass().getName());
		System.out.println("  V      : " + v.getClass().getName());
	}

	T getT() {
		return t;
	}

	V getV() {
		return v;
	}

	public static void main(String args[]) {
		MoreParameters<Integer, Double> tv; //            
		//                ,          
		tv = new MoreParameters<Integer, Double>(100, 12.56);
		tv.printTypes();
		int num = tv.getT();
		System.out.println("num      : " + num);
		double dou = tv.getV();
		System.out.println("dou      :" + dou);
	}

}

 
인 스 턴 스 257 경계 형식 프로그램 예제
//        
public class BoundedType {
	public static void main(String args[]) {
		System.out.println("          :");
		Integer inums[] = { 1, 2, 3, 4, 5 };//    Integer     
		MyTypes<Integer> iobj = new MyTypes<Integer>(inums);//      
		System.out.println("\tint         :" + iobj.summation());
		Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
		MyTypes<Double> dobj = new MyTypes<Double>(dnums);//    Double    
		System.out.println("
\tdouble :" + dobj.summation()); } } class MyTypes<T extends Number> { T[] nums;// Number MyTypes(T[] obj) {// nums = obj; } double summation() {// double sum = 0.0; for (int i = 0; i < nums.length; ++i) sum += nums[i].doubleValue(); // Number double return sum ; } }

 
실례 258 어댑터 사용 예시
import java.util.*;

//         
public class Wildcard {
	public static void main(String args[]) {
		Integer Ints[] = { 1, 2, 3, 4, 5 };//   Integer        
		Symbol<Integer> integer = new Symbol<Integer>(Ints);//   Integer    
		Double Dous[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };//   Double        
		Symbol<Double> douObject = new Symbol<Double>(Dous);//   Double    
		douObject.printMessage(integer); // integer douObject      
		List<String> list1 = new ArrayList<String>();//     List    ,      String   
		//  List       
		list1.add("String");
		list1.add("  ");
		list1.add("     ");
		List<?> list2 = list1;//     List               ,  list1  list2
		System.out.println("  List  list2      :");
		for (int i = 0; i < list2.size(); i++) {
			System.out.println("\t" + list2.get(i));//  list2      
		}
	}

}

class Symbol<T extends Number> {
	T[] nums;

	Symbol(T[] obj) {
		nums = obj;
	}

	void printMessage(Symbol<?> sb) { //           
		System.out.println("     sb      :" + sb.getClass().getName());
	}

}

 
실례 259 범 형 방법 사용 예시
import java.util.Date;

//         
public class GenericMethod {
	//       ,            T   
	public static <T> void genericMethods(T t, char n) {
		T t1 = t; //             T   
		System.out.println("[1] " + n + "      :" + t1.getClass().getName());
	}

	public static <T> void genericMethods(T t) {
		System.out.println("
[2] " + t + " :" + t.getClass().getName()); } public static void main(String args[]) { Date date = new Date(); Character k = new Character('A'); // GenericMethod.<Character> genericMethods(k, 'B'); genericMethods(date); } }

 
인 스 턴 스 260 팬 인터페이스 예제
//         
public class GenericInterface {
	public static void main(String args[]) {
		Double doubleArrays[] = { 56.5, 58.127, 56.2, 5.569, 825.0, 12.36,
				510.89 };//     Double         
		Character charArrays[] = { 'A', 'w', 'z', 'Z', 'b', 'u', 'x' };//     Character         
		ComparableElement<Double> iob = new ComparableElement<Double>(
				doubleArrays);//   Double       
		ComparableElement<Character> cob = new ComparableElement<Character>(
				charArrays);//   Character       
		//   MaxOrMin    min() max()
		System.out.println(" Integer   ,      ,max= " + iob.max());
		System.out.println(" Integer   ,       ,min= " + iob.min());
		System.out.println(" Character   ,      ,max= " + cob.max());
		System.out.println(" Character   ,       ,min=  " + cob.min());
	}

}

interface MaxOrMin<T extends Comparable<T>> {//         
	//         :min() max()
	T min();

	T max();
}

//     ComparableElement    Comparable    MaxOrMin  
class ComparableElement<T extends Comparable<T>> implements MaxOrMin<T> {
	T[] mm;

	ComparableElement(T[] ob) {
		mm = ob;
	}

	public T min() {//   MaxOrMin    min()  ,         
		T t = mm[0];
		for (int i = 1; i < mm.length; ++i)
			if (mm[i].compareTo(t) < 0)
				t = mm[i];
		return t;
	}

	public T max() {//   MaxOrMin    max()  ,         
		T t = mm[0];
		for (int i = 1; i < mm.length; ++i)
			if (mm[i].compareTo(t) > 0)
				t = mm[i];
		return t;
	}
}

 
실례 261 범 형 좌표 인쇄 실현
/**
 * Created by IntelliJ IDEA. User: leizhimin Date: 2007-9-18 Time: 16:09:37
 *     ,         
 */
public class CoorGeneric {
	static void showXY(GenericCoords<?> c) {//       ,         C    XL    XL    X Y  
		System.out.println("X Y    :");
		for (int i = 0; i < c.gcs.length; i++) {
			System.out.println(c.gcs[i].x + "  " + c.gcs[i].y);
		}
	}

	static void showXYZ(GenericCoords<? extends XYZ> c) {
		System.out.println("X Y Z    :");
		//       ,         C    XYZ    XYZ    X、Y Z  
		for (int i = 0; i < c.gcs.length; i++) {
			System.out.println(c.gcs[i].x + "  " + c.gcs[i].y + "  "
					+ c.gcs[i].z);
		}
	}

	static void showAll(GenericCoords<? extends XYZT> c) {
		System.out.println("X Y Z T    :");
		//       ,         C    XYZT    XYZT    X、Y、Z T  
		for (int i = 0; i < c.gcs.length; i++) {
			System.out.println(c.gcs[i].x + "  " + c.gcs[i].y + "  "
					+ c.gcs[i].z + "  " + c.gcs[i].t);
		}
	}

	public static void main(String args[]) {
		XY td[] = { new XY(0, 0), new XY(7, 9), new XY(18, 4), new XY(-1, -23) };
		GenericCoords<XY> gcd1 = new GenericCoords<XY>(td);
		System.out.println("GenericCoords   gcd2    :");
		showXY(gcd1);
		XYZT fd[] = { new XYZT(1, 2, 3, 4), new XYZT(6, 8, 14, 8),
				new XYZT(22, 9, 4, 9), new XYZT(3, -2, -23, 17) };
		GenericCoords<XYZT> gcd2 = new GenericCoords<XYZT>(fd);
		System.out.println("GenericCoords   gcd2    :");
		showXY(gcd2);
		showXYZ(gcd2);
		showAll(gcd2);
	}
}

class XY {//     XY    
	int x, y;

	public XY(int x, int y) {//    X、Y  
		this.x = x;
		this.y = y;
	}
}

class XYZ extends XY {//     XYZ    
	int z;

	public XYZ(int x, int y, int z) {
		super(x, y);//          
		this.z = z;
	}
}

class XYZT extends XYZ {//     XYZT    ,  X:   ,Y:    Z:    ,T:  
	int t;

	public XYZT(int x, int y, int z, int t) {
		super(x, y, z);//          
		this.t = t;
	}
}

/**
 *        (    ) 
 */
class GenericCoords<T extends XY> {//      ,        XY
	T[] gcs;

	public GenericCoords(T[] gcs) {
		this.gcs = gcs;
	}
}

 
14.2 범 형 류 의 계승
실례 262 계승 범 형 클래스 예시
import java.util.Date;

//     
public class GenericClass {
	public static void main(String args[]) {
		System.out.println("              :");
		//        ,         ,Date     ,    String  
		Child<Date, String> cd = new Child<Date, String>(new Date(),
				"        : ");
		System.out.print("\t" + cd.getDob());
		System.out.println(cd.getOb());
	}

}

class Child<T, U> extends Father<T> {
	U u;

	public Child(T t1, U u1) {
		super(t1); //        
		u = u1; //         
	}

	public U getDob() {
		return u;
	}
}

class Father<T> { //        
	T t;

	public Father(T t) {
		this.t = t;
	}

	public Father() {
		t = null;
	}

	public T getOb() {
		return t;
	}
}

 
실례 263 비 범 형 클래스 계승 예시
//        
public class NonGenericcClass {
	public static void main(String args[]) {
		System.out.println("             :");
		doNonGeneric<String> oa = new doNonGeneric<String>(
				"doNonGeneric    : ", 125);
		System.out.print("\t" + oa.getOb());
		System.out.println(oa.getNum());
	}

}

class NonGeneric {//       ,        
	double num;

	public NonGeneric(double n) {//     num          
		num = n;
	}

	public NonGeneric() {//     num     0.0
		num = 0.0;
	}

	public double getNum() {//     num    
		return num;
	}
}

class doNonGeneric<T> extends NonGeneric {//        NonGeneric   。         
	T ob;

	public doNonGeneric(T ob, double n) {
		super(n);//            
		this.ob = ob;//              
	}

	public T getOb() {
		return ob;
	}
}

 
실례 264 범 형 류 의 유형 식별 예시
//          1
public class GenericRTTI {
	public static void main(String args[]) {
		MyFirstGeneric<Double> dou = new MyFirstGeneric<Double>(100.0);
		MyFirstGeneric<String> str = new MyFirstGeneric<String>("hellow");
		if (dou instanceof MyFirstGeneric)//  dou   MyFirstGeneric    
			System.out
					.println("MyFirstGeneric<Integer> object is instance of MyFirstGeneric");
		if (dou instanceof MyFirstGeneric<?>)//  dou   MyFirstGeneric<?>      
			System.out
					.println("MyFirstGeneric<Integer> object is instance of MyFirstGeneric<?>");
		if (dou.getClass() == str.getClass())//                
			System.out
					.println("MyFirstGeneric<Integer> class equals MyFirstGeneric<String> class");
	}

}

 
인 스 턴 스 265 강제 형식 변환 예제
//      
public class CastType {
	public static void main(String args[]) {
		Father<Double> father = new Father<Double>(1.0);
		Child<Double, String> child = new Child<Double, String>(200.0, "    ");
		//             ,  
		if ((Father<Double>) child instanceof Father)
			System.out.println("           .");
		//             ,  
		try {
			if ((Child<Double, String>) father instanceof Child)
				System.out.println("           .");
		} catch (Exception e) {
			System.out.println(e);
			System.out.println("       :               .");

		}
	}
}

 
닦다
인 스 턴 스 266 무한 계 의 닦 기
import java.util.Date;

//      
public class BorderWipe<T extends Date> {
	//      T  String   
	T date;

	BorderWipe(T date) {
		this.date = date;
	}

	T getOb() {
		return date;
	}

}

 
실례 267 한계 닦 기
//      
public class UnBorderWipe<T> {
	//      T  Object   
	T ob;

	UnBorderWipe(T ob) {
		this.ob = ob;
	}

	T getOb() {
		return ob;
	}

}

 
14.4 집합 범 형 류
인 스 턴 스 268 Hashtable 의 일반화
import java.util.Hashtable;

//Hashtable    
public class HashtableGeneric<K, V> {
	//   Hashtable      
	public Hashtable<K, V> hashTable = new Hashtable<K, V>();

	//   put   key value  
	public void put(K k, V v) {
		hashTable.put(k, v);
	}

	//   get      key   value  
	public V get(K k) {
		return hashTable.get(k);
	}

	public static void main(String args[]) {
		HashtableGeneric<String, String> t = new HashtableGeneric<String, String>();
		t.put("key", "Java  ");
		String s = t.get("key");
		System.out.println("  key    value   :
\t" + s); } }

 
인 스 턴 스 269 다기 능 붓
import java.awt.*;
import java.awt.event.*;
import java.util.*;

//     
public class Paintbrush extends Frame{
	private final static int POINT = 0;

	private final static int LINE = 1;

	private final static int RECTANGLE = 2;

	private final static int OVAL = 3;

	private int type; //     

	Point p1;

	Point p2;

	ArrayList<Point> points = new ArrayList<Point>();

	ArrayList<DrawPoint> area = new ArrayList<DrawPoint>();

	public Paintbrush(String s) {
		super(s);
	}

	public void mainFrame() {
		MenuBar menuBar = new MenuBar();

		Menu menu = new Menu("  ");
		MenuItem fmi4 = new MenuItem("Exit");
		fmi4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		menu.addSeparator();
		menu.add(fmi4);

		Menu mtype = new Menu("    ");
		MenuItem menuItem = new MenuItem("  ");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				type = Paintbrush.POINT;
			}
		});
		MenuItem menuItem2 = new MenuItem("  ");
		menuItem2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				type = Paintbrush.LINE;
			}
		});
		MenuItem dmi3 = new MenuItem("  ");
		dmi3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				type = Paintbrush.RECTANGLE;
			}
		});
		MenuItem dmi4 = new MenuItem("  ");
		dmi4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				type = Paintbrush.OVAL;
			}
		});
		mtype.add(menuItem);
		mtype.add(menuItem2);
		mtype.add(dmi3);
		mtype.add(dmi4);

		menuBar.add(menu);
		menuBar.add(mtype);

		setMenuBar(menuBar);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				p1 = new Point(e.getX(), e.getY());
				if (type == Paintbrush.POINT) {
					points.add(p1);
					repaint();
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (type != Paintbrush.POINT) {
					p2 = new Point(e.getX(), e.getY());
					area.add(new DrawPoint(p1, p2, type));
					repaint();
				}
			}
		});

		setBounds(50, 50, 640, 480);
		setBackground(Color.WHITE);
		setVisible(true);
	}

	public void paint(Graphics g) {
		Iterator<Point> ip = points.iterator(); //     
		g.setColor(Color.black);
		while (ip.hasNext()) {
			Point p = ip.next(); //     
			g.fillOval(p.x, p.y, 10, 10);
		}

		//      
		int x1, y1, x2, y2;
		for (Iterator<DrawPoint> ipp = area.iterator(); ipp.hasNext();) {
			DrawPoint pp = ipp.next();

			x1 = (int) pp.startPoint.getX();
			y1 = (int) pp.startPoint.getY();
			x2 = (int) pp.endPoint.getX();
			y2 = (int) pp.endPoint.getY();

			switch (pp.type) {
			case LINE:
				g.setColor(Color.green);
				g.drawLine(x1, y1, x2, y2);
				break;
			case RECTANGLE:
				g.setColor(Color.red);
				g.drawRect(x1, y1, x2 - x1, y2 - y1);
				//              ,       :     
				break;
			case OVAL:
				g.setColor(Color.blue);
				g.drawOval(x1, y1, x2 - x1, y2 - y1);
				break;
			default:
				break;
			}
		}
	}

	public static void main(String[] args) {
		Paintbrush drawApp = new Paintbrush("       ");
		drawApp.mainFrame();
	}
}
class DrawPoint {
	public Point startPoint;

	public Point endPoint;

	public int type;

	public DrawPoint(Point sPoint, Point ePoint, int drawType) {
		startPoint = sPoint;
		endPoint = ePoint;
		type = drawType;
	}
}

좋은 웹페이지 즐겨찾기