Java中日期转换、加减
package com.youwei.common;
import java.text.*;
import java.util.*;
public class CDate {
public static Date toDate(String cDate) throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat(”yyyy-MM-dd”);
return fmt.parse(cDate);
}
public static Date changeDay(Date date, int offset) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_YEAR,
(calendar.get(Calendar.DAY_OF_YEAR) + offset));
return calendar.getTime();
}
}
java保留两位小数
double c=3.154215;
java.text.DecimalFormat myformat=new java.text.DecimalFormat(”0.00″);
String str = myformat.format(c);
java小数点问题:
方式一:
四舍五入
double f = 111231.5585;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
保留两位小数
方式二:
java.text.DecimalFormat df =new java.text.DecimalFormat(”#.00″);
df.format(你要格式化的数字);
例:new java.text.DecimalFormat(”#.00″).format(3.1415926)
#.00 表示两位小数 #.0000四位小数 以此类推…
方式三:
double d = 3.1415926;
String result = String .format(”%.2f”);
%.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。
Java MD5加密
- package cn.org.jshuwei.j2ee.util;
- import java.security.MessageDigest;
- /**
- *
- * MD5加密工具类
- *
- * @author huwei(jshuwei.org.cn)
- * @since 1.4
- *
- */
- public class MD5 {
- private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
- "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
- private static String byteArrayToHexString(byte[] bytes) {
- StringBuffer sb = new StringBuffer();
- for (byte b : bytes) {
- sb.append(byteToHexString(b));
- }
- return sb.toString();
- }
- private static String byteToHexString(byte b) {
- int n = b;
- if (n < 0)
- n = 256 + n;
- int d1 = n / 16;
- int d2 = n % 16;
- return hexDigits[d1] + hexDigits[d2];
- }
- /**
- * 将字符串加密成MD5字符串
- *
- * @param origin
- * 需要加密的字符串
- * @return 加密后的字符串
- */
- public static String MD5Encode(String origin) {
- String ret = null;
- try {
- ret = new String(origin);
- MessageDigest md = MessageDigest.getInstance("MD5");
- ret = byteArrayToHexString(md.digest(ret.getBytes()));
- } catch (Exception e) {
- }
- return ret;
- }
- }
Java时间处理
Java时间处理API很丰富,但有时候调用起来不方便。本文代码封装了一些常用的时间处理,方便开发时调用。
- package cn.org.jshuwei.j2ee.util;
- import java.sql.Date;
- import java.text.DateFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- /**
- *
- * 日期操作的工具类
- *
- * @author huwei(jshuwei.org.cn)
- * @since 1.0
- *
- */
- public class DateUtil {
- private static String defDtPtn = "yyyy-MM-dd HH:mm:ss";// 缺省日期格式
- /**
- * 计算给定时间至今的天数
- *
- * @since 1.1
- * @param date
- * 给定的时间
- * @return 给定时间至今的天数
- */
- public static long date2day(String date) {
- long day = 0;
- DateFormat df = DateFormat.getDateInstance();
- try {
- long old = df.parse(date).getTime();
- long now = new java.util.Date().getTime();
- long secs = now - old;
- day = secs / (1000 * 24 * 60 * 60);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return day;
- }
- /**
- * 格式化给定时间后day天的时间
- *
- * @since 1.0
- * @param date
- * 需要格式化的时间
- * @param day
- * 增加的天数
- * @return 给定时间的后day天的格式化字符串(如:2008-11-22)
- */
- public static String formatDate(java.util.Date date, Integer day) {
- String str = "";
- str = new Date(date.getTime() + day * 24 * 60 * 60).toString();
- return str;
- }
- /**
- * 格式化给定时间
- *
- * @param date
- * 需要格式化的时间
- * @return 给定时间的格式化字符串(如:2008-11-22)
- */
- public static String formatDate(java.util.Date date) {
- return new Date(date.getTime()).toString();
- }
- /**
- * 得到当前年
- *
- * @since 1.0
- * @return 返回当前年(YYYY)
- */
- public static int getYear() {
- return Calendar.getInstance().get(Calendar.YEAR);
- }
- /**
- * 得到当前月
- *
- * @since 1.0
- * @return 返回当前月(1~12)
- */
- public static int getMonth() {
- return Calendar.getInstance().get(Calendar.MONTH) + 1;
- }
- /**
- * 得到当前日
- *
- * @since 1.0
- * @return 返回当前日(1~31)
- */
- public static int getDay() {
- return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
- }
- /**
- * 得到当前年
- *
- * @since 1.0
- * @return 返回当前年(YY)
- */
- public static String getYear2() {
- int year = getYear();
- return StringUtil.Integer2String(year, "1986").substring(2, 4);
- }
- /**
- * 得到当前月
- *
- * @since 1.0
- * @return 返回当前月(01~12)
- */
- public static String getMonth2() {
- int month = getMonth();
- if (month < 10) {
- return "0" + StringUtil.Integer2String(month, "00");
- }
- return StringUtil.Integer2String(month, "00");
- }
- /**
- * 得到当前日
- *
- * @since 1.0
- * @return 返回当前日(01~31)
- */
- public static String getDay2() {
- int day = getDay();
- if (day < 10) {
- return "0" + StringUtil.Integer2String(day, "00");
- }
- return StringUtil.Integer2String(day, "00");
- }
- /**
- * 得到指定格式的当前时间
- *
- * @param format
- * 格式化形式(年用YY/YYYY表示;月用M/MM表示;日用D/DD表示,之间任意任序组合),<br />
- * 如"YYYY-MM-DD"返回形如:1986-12-17<br />
- * 如"YY-MM"返回形如:86-12<br />
- * 如"YY年MM月"返回形如:86年12月……
- * @since 1.0
- * @return 返回指定格式的当前时间
- *
- */
- public static String getDate(String format) {
- format = format.replace("YYYY", getYear() + "");
- format = format.replace("YY", getYear2());
- format = format.replace("MM", getMonth2());
- format = format.replace("M", getMonth() + "");
- format = format.replace("DD", getDay2());
- format = format.replace("D", getDay() + "");
- return format;
- }
- /**
- * 将字符串按指定格式解析成日期对象
- *
- * @since 1.1
- * @param dateStr
- * 需要进行转换的日期字符串
- * @param pattern
- * 日期字符串的格式
- * @return "yyyy-MM-dd HH:mm:ss"形式的日期对象
- */
- public static java.util.Date parseDate(String dateStr, String pattern) {
- SimpleDateFormat DATEFORMAT = new SimpleDateFormat(defDtPtn);
- DATEFORMAT.applyPattern(pattern);
- java.util.Date ret = null;
- try {
- ret = DATEFORMAT.parse(dateStr);
- } catch (Exception e) {
- e.printStackTrace();
- }
- DATEFORMAT.applyPattern(defDtPtn);
- return ret;
- }
- /**
- * 计算详细年龄
- *
- * @since 1.1
- * @param birthdayStr
- * 出生日期 格式"YYYY-MM-DD"
- * @return 指定日期至今天的年龄
- */
- public static String countAge(String birthdayStr) {
- String age = "";
- if (birthdayStr != null && birthdayStr.length() == 8) {
- java.util.Date birthday = parseDate(birthdayStr, "YYYY-MM-DD");
- if (birthday != null) {
- Calendar calendar = Calendar.getInstance();
- int year1 = getYear();
- int month1 = StringUtil.String2Integer(getMonth2(), 0);
- int day1 = StringUtil.String2Integer(getDay2(), 00);
- calendar.setTime(birthday);
- int year2 = calendar.get(Calendar.YEAR);
- int month2 = calendar.get(Calendar.MONTH) + 1;
- int day2 = calendar.get(Calendar.DATE);
- int year = year1 - year2;
- int month = month1 - month2;
- int day = day1 - day2;
- if (month < 0) {
- year = year - 1;
- month = 12 + month1 - month2;
- }
- if (day < 0) {
- month = month - 1;
- if (month < 0) {
- year = year - 1;
- month = 11;
- }
- int lastMonthDay = 0;
- if (month1 == 0) {
- lastMonthDay = getDayOfMonth(12, year1 - 1);
- } else {
- lastMonthDay = getDayOfMonth(month1, year1);
- }
- day = lastMonthDay + day1 - day2;
- }
- if (year > 5) {
- age = year + "岁";
- } else if (year > 0) {
- if (month == 0) {
- age = year + "岁";
- } else {
- age = year + "岁" + month + "月";
- }
- } else {
- if (month > 5) {
- age = month + "月";
- } else if (month > 0) {
- age = month + "月" + day + "天";
- } else {
- age = day + "天";
- }
- }
- }
- }
- return age;
- }
- /**
- * 得到指定年月的天数
- *
- * @since 1.1
- * @param month
- * 指定月份
- * @param year
- * 指定的年份
- * @return 天数
- */
- public static int getDayOfMonth(int month, int year) {
- int ret = 0;
- boolean flag = false;
- if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
- flag = true;
- }
- switch (month) {
- case 1:
- ret = 31;
- break;
- case 2:
- if (flag) {
- ret = 29;
- } else {
- ret = 28;
- }
- break;
- case 3:
- ret = 31;
- break;
- case 4:
- ret = 30;
- break;
- case 5:
- ret = 31;
- break;
- case 6:
- ret = 30;
- break;
- case 7:
- ret = 31;
- break;
- case 8:
- ret = 31;
- break;
- case 9:
- ret = 30;
- break;
- case 10:
- ret = 31;
- break;
- case 11:
- ret = 30;
- break;
- case 12:
- ret = 31;
- break;
- default:
- break;
- }
- return ret;
- }
- /**
- * 计算某天是星期几
- *
- * @since 1.1
- * @param p_date
- * 日期字符串
- * @return 星期
- */
- public static int whatDayIsSpecifyDate(String p_date) {
- // 2002-2-22 is friday5
- long differenceDays = 0L;
- long m = 0L;
- differenceDays = signDaysBetweenTowDate(p_date, "2002-2-22");
- m = (differenceDays % 7);
- m = m + 5;
- m = m > 7 ? m - 7 : m;
- return Integer.parseInt(m + "");
- }
- /**
- * 计算两日期间相差天数.
- *
- * @since 1.1
- * @param d1
- * 日期字符串
- * @param d2
- * 日期字符串
- * @return long 天数
- */
- public static long signDaysBetweenTowDate(String d1, String d2) {
- java.sql.Date dd1 = null;
- java.sql.Date dd2 = null;
- long result = -1l;
- try {
- dd1 = java.sql.Date.valueOf(d1);
- dd2 = java.sql.Date.valueOf(d2);
- result = signDaysBetweenTowDate(dd1, dd2);
- } catch (Exception ex) {
- result = -1;
- }
- return result;
- }
- /**
- * 计算两日期间相差天数.
- *
- * @since 1.1
- * @param d1
- * 开始日期 日期型
- * @param d2
- * 结束日期 日期型
- * @return long 天数
- */
- public static long signDaysBetweenTowDate(java.sql.Date d1, java.sql.Date d2) {
- return (d1.getTime() - d2.getTime()) / (3600 * 24 * 1000);
- }
- }
Java数组操作
- package cn.org.jshuwei.j2ee.util;
- /**
- *
- * 数组操作的工具类(以int型数组为例)
- *
- * <b>排序算法的分类如下:</b><br /> 1.插入排序(直接插入排序、折半插入排序、希尔排序); <br />
- * 2.交换排序(冒泡泡排序、快速排序);<br /> 3.选择排序(直接选择排序、堆排序);<br /> 4.归并排序; <br /> 5.基数排序。<br
- * />
- *
- * <b>关于排序方法的选择:</b><br /> (1)若n较小(如n≤50),可采用直接插入或直接选择排序。<br />
- * (2)若文件初始状态基本有序(指正序),则应选用直接插人、冒泡或随机的快速排序为宜;<br />
- * (3)若n较大,则应采用时间复杂度为O(nlgn)的排序方法:快速排序、堆排序或归并排序。<br />
- *
- * @author huwei(jshuwei.org.cn)
- * @since 1.1
- *
- */
- public class ArrayUtil {
- /**
- * 交换数组中两元素
- *
- * @since 1.1
- * @param ints
- * 需要进行交换操作的数组
- * @param x
- * 数组中的位置1
- * @param y
- * 数组中的位置2
- * @return 交换后的数组
- */
- public static int[] swap(int[] ints, int x, int y) {
- int temp = ints[x];
- ints[x] = ints[y];
- ints[y] = temp;
- return ints;
- }
- /**
- * 冒泡排序 方法:相邻两元素进行比较 性能:比较次数O(n^2),n^2/2;交换次数O(n^2),n^2/4
- *
- * @since 1.1
- * @param source
- * 需要进行排序操作的数组
- * @return 排序后的数组
- */
- public static int[] bubbleSort(int[] source) {
- for (int i = 1; i < source.length; i++) {
- for (int j = 0; j < i; j++) {
- if (source[j] > source[j + 1]) {
- swap(source, j, j + 1);
- }
- }
- }
- return source;
- }
- /**
- * 直接选择排序法 方法:每一趟从待排序的数据元素中选出最小(或最大)的一个元素, 顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
- * 性能:比较次数O(n^2),n^2/2 交换次数O(n),n
- * 交换次数比冒泡排序少多了,由于交换所需CPU时间比比较所需的CUP时间多,所以选择排序比冒泡排序快。
- * 但是N比较大时,比较所需的CPU时间占主要地位,所以这时的性能和冒泡排序差不太多,但毫无疑问肯定要快些。
- *
- * @since 1.1
- * @param source
- * 需要进行排序操作的数组
- * @return 排序后的数组
- */
- public static int[] selectSort(int[] source) {
- for (int i = 0; i < source.length; i++) {
- for (int j = i + 1; j < source.length; j++) {
- if (source[i] > source[j]) {
- swap(source, i, j);
- }
- }
- }
- return source;
- }
- /**
- * 插入排序 方法:将一个记录插入到已排好序的有序表(有可能是空表)中,从而得到一个新的记录数增1的有序表。 性能:比较次数O(n^2),n^2/4
- * 复制次数O(n),n^2/4 比较次数是前两者的一般,而复制所需的CPU时间较交换少,所以性能上比冒泡排序提高一倍多,而比选择排序也要快。
- *
- * @since 1.1
- * @param source
- * 需要进行排序操作的数组
- * @return 排序后的数组
- */
- public static int[] insertSort(int[] source) {
- for (int i = 1; i < source.length; i++) {
- for (int j = i; (j > 0) && (source[j] < source[j - 1]); j--) {
- swap(source, j, j - 1);
- }
- }
- return source;
- }
- /**
- * 快速排序 快速排序使用分治法(Divide and conquer)策略来把一个序列(list)分为两个子序列(sub-lists)。 步骤为:
- * 1. 从数列中挑出一个元素,称为 "基准"(pivot), 2.
- * 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面
- * (相同的数可以到任一边)。在这个分割之后,该基准是它的最后位置。这个称为分割(partition)操作。 3.
- * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
- * 递回的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了
- * 。虽然一直递回下去,但是这个算法总会结束,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。
- *
- * @since 1.1
- * @param source
- * 需要进行排序操作的数组
- * @return 排序后的数组
- */
- public static int[] quickSort(int[] source) {
- return qsort(source, 0, source.length - 1);
- }
- /**
- * 快速排序的具体实现,排正序
- *
- * @since 1.1
- * @param source
- * 需要进行排序操作的数组
- * @param low
- * 开始低位
- * @param high
- * 结束高位
- * @return 排序后的数组
- */
- private static int[] qsort(int source[], int low, int high) {
- int i, j, x;
- if (low < high) {
- i = low;
- j = high;
- x = source[i];
- while (i < j) {
- while (i < j && source[j] > x) {
- j--;
- }
- if (i < j) {
- source[i] = source[j];
- i++;
- }
- while (i < j && source[i] < x) {
- i++;
- }
- if (i < j) {
- source[j] = source[i];
- j--;
- }
- }
- source[i] = x;
- qsort(source, low, i - 1);
- qsort(source, i + 1, high);
- }
- return source;
- }
- /**
- * 二分法查找 查找线性表必须是有序列表
- *
- * @since 1.1
- * @param source
- * 需要进行查找操作的数组
- * @param key
- * 需要查找的值
- * @return 需要查找的值在数组中的位置,若未查到则返回-1
- */
- public int binarySearch(int[] source, int key) {
- int low = 0, high = source.length - 1, mid;
- while (low <= high) {
- mid = (low + high) >>> 1;
- if (key == source[mid]) {
- return mid;
- } else if (key < source[mid]) {
- high = mid - 1;
- } else {
- low = mid + 1;
- }
- }
- return -1;
- }
- /**
- * 反转数组
- *
- * @since 1.1
- * @param source
- * 需要进行反转操作的数组
- * @return 反转后的数组
- */
- public static int[] reverse(int[] source) {
- int length = source.length;
- int temp = 0;
- for (int i = 0; i < length / 2; i++) {
- temp = source[i];
- source[i] = source[length - 1 - i];
- source[length - 1 - i] = temp;
- }
- return source;
- }
- }
Java Applet
Java Applet 是用Java 语言编写的一些小应用程序,这些程序是直接嵌入到页面中,由支持Java的浏览器(IE 或 Nescape)解释执行能够产生特殊效果的程序。它可以大大提高Web页面的交互能力和动态执行能力。包含Applet的网页被称为Java-powered页,可以称其为Java支持的网页。
当用户访问这样的网页时,Applet被下载到用户的计算机上执行,但前提是用户使用的是支持Java的网络浏览器。由于Applet是在用户的计算机上执行的,所以它的执行速度不受网络带宽或者Modem存取速度的限制,用户可以更好地欣赏网页上Applet产生的多媒体效果。
Applet 小应用程序的实现主要依靠java.applet 包中的Applet类。与一般的应用程序不同,Applet应用程序必须嵌入在HTML页面中,才能得到解释执行;同时Applet可以从Web页面中获得参数,并和Web页面进行交互。
含有Applet的网页的HTML文件代码中必须带有<applet>和</applet>这样一对标记,当支持Java的网络浏览器遇到这对标记时,就将下载相应的小程序代码并在本地计算机上执行该Applet小程序。
Applet是一种Java的小程序,它通过使用该Applet的HTML文件,由支持Java的网页浏览器下载运行。也可以通过java开发工具的appletviewer来运行。Applet 程序离不开使用它的HTML文件。这个HTML文件中关于Applet的信息至少应包含以下三点:
1)字节码文件名(编译后的Java文件,以.class为后缀)
2)字节码文件的地址
3)在网页上显示Applet的方式。
一个HTML文件增加Applet有关的内容只是使网页更加富有生气,如添加声音、动画等这些吸引人的特征,它并不会改变HTML文件中与Applet无关的元素。
(一) Applet程序开发步骤
Applet程序开发主要步骤如下:
1)选用EDIT或Windows Notepad等工具作为编辑器建立Java Applet源程序。
2)把Applet的源程序转换为字节码文件。
3)编制使用class 的HTML文件。在HTML文件内放入必要的<APPLET>语句。
下面举一个最简单的HelloWorld 例子来说明Applet程序的开发过程:
(1) 编辑Applet 的java源文件
创建文件夹C:/ghq,在该文件夹下建立 HelloWorld.java
文件的源代码如下:
import java.awt.*; import java.applet.*; public class HelloWorld extends Applet //继承Appelet类,这是Appelet Java程序的特点 { public void paint(Graphics g ) { g.drawString("Hello World!",5,35); } } |
保存上述程序在C:/ghq/HelloWorld.java文件里。
(2)编译Applet
编译HelloWorld.java源文件可使用如下JDK命令:
C:/ghq/>javac HelloWorld.java<Enter>
注意:如果编写的源程序违反了Java编程语言的语法规则,Java编译器将在屏幕上显示语法错误提示信息。源文件中必须不含任何语法错误,Java编译器才能成功地把源程序转换为appletviewer和浏览器能够执行的字节码程序。
成功地编译Java applet之后生成响应的字节码文件HelloWorld.class的文件。用资源管理器或DIR命令列出目录列表,将会发现目录C:/ghq中多了一个名为HelloWorld.class的文件。
(3)创建HTML文件
在运行创建的HelloWorld.class 之前,还需创建一个HTML文件,appletviewer或浏览器将通过该文件访问创建的Applet。为运行HelloWorld.class, 需要创建包含如下HTML语句的名为HelloWorld.html的文件。
<HTML> <TITLE>HelloWorld! Applet</TITLE> <APPLET CODE="JavaWorld.class" WIDTH=200 HEIGHT=100> </APPLET> </HTML> |
本例中,<APPLET>语句指明该Applet字节码类文件名和以像素为单位的窗口的尺寸。虽然这里HTML文件使用的文件名为HelloWorld.HTML,它对应于HelloWorld.java的名字,但这种对应关系不是必须的,可以用其他的任何名字(比如说Ghq.HTML)命名该HTML文件。但是使文件名保持一种对应关系可给文件的管理带来方便。
(4)执行 HelloWorld.html
如果用appletviewer运行HelloWorld.html,需输入如下的命令行:
C:/ghq/>appletviewer JavaWorld.html<ENTER>
可以看出,该命令启动了appletviewer并指明了HTML文件,该HTML文件中包含对应于HelloWorld 的<APPLET>语句。
如果用浏览器运行HelloWorld Applet,需在浏览器的地址栏中输入HTML文件URL地址。
至此,一个Applet程序的开发运行整个过程结束了(包括java源文件、编译的class文件、html文件以及用appletviewer或用浏览器运行)。
Java接口和抽象类
在没有好好地研习面向对象设计的设计模式之前,我对Java接口和Java抽象类的认识还是很模糊,很不可理解。刚学Java语言时,就很难理解为什么要有接口这个概念。
虽说是可以实现所谓的多继承,可一个只有方法名,没有方法体的东西,我实现它又有什么用呢?我从它那什么也得不到,除了一些方法名,我直接在具体类里加入这些方法不就行了吗?
为什么一定要有抽象类这个概念?为什么就不能把这个父类写成一个具体的类,子类再继承它不就可以了吗?何必弄一个抽象类出来,还要弄一些没有方法体的抽象方法,弄得又象接口又象类的,让人捉摸不定。
当我开始学习java设计模式,真正走进面向对象设计的大门之后,我才发现,自己对面向对象设计的理解原来是那么的片面,那么的肤浅,根本就没有真正理解面向对象思想的精髓,在某一种程度上还受着面向过程的影响,以为弄出了一个个类,就算是面向对象了,而其实还是被过程所驱使着。我还是说说我现在对面向对象思想的理解吧,不一定正确全面,但我想应该还算是比以前略有进步吧,面向对象思想,我觉得最关键的就是抽象。
一个软件设计的好坏,我想很大程度上取决于它的整体架构,而这个整体架构其实就是你对整个宏观商业业务的抽象框架,当代表业务逻辑的高层抽象层结构合理时,你底层的具体实现需要考虑的就仅仅是一些算法和一些具体的业务实现了。当你需要再开发另一个相近的项目时,你以前的抽象层说不定还可以再次利用呢,面对对象的设计,复用的重点其实应该是抽象层的复用,而不是具体某一个代码块的复用,是不是一下子感觉自己对复用理解的高度又上升了一层?
说到了抽象,就不能不提到曾让我头痛的Java接口和Java抽象类了,这也是本文我想说的重点。既然面向对象设计的重点在于抽象,那Java接口和Java抽象类就有它存在的必然性了。
Java接口和Java抽象类代表的就是抽象类型,就是我们需要提出的抽象层的具体表现。OOP面向对象的编程,如果要提高程序的复用率,增加程序的可维护性,可扩展性,就必须是面向接口的编程,面向抽象的编程,正确地使用接口、抽象类这些太有用的抽象类型做为你结构层次上的顶层,Java接口和Java抽象类有太多相似的地方,又有太多特别的地方,究竟在什么地方,才是它们的最佳位置呢?把它们比较一下,你就可以发现了。
1、Java接口和Java抽象类最大的一个区别,就在于Java抽象类可以提供某些方法的部分实现,而Java接口不可以,这大概就是Java抽象类唯一的优点吧,但这个优点非常有用。
如果向一个抽象类里加入一个新的具体方法时,那么它所有的子类都一下子都得到了这个新方法,而Java接口做不到这一点,如果向一个Java接口里加入一个新方法,所有实现这个接口的类就无法成功通过编译了,因为你必须让每一个类都再实现这个方法才行,这显然是Java接口的缺点。
2、一个抽象类的实现只能由这个抽象类的子类给出,也就是说,这个实现处在抽象类所定义出的继承的等级结构中,而由于Java语言的单继承性,所以抽象类作为类型定义工具的效能大打折扣。
在这一点上,Java接口的优势就出来了,任何一个实现了一个Java接口所规定的方法的类都可以具有这个接口的类型,而一个类可以实现任意多个Java接口,从而这个类就有了多种类型。
3、从第2点不难看出,Java接口是定义混合类型的理想工具,混合类表明一个类不仅仅具有某个主类型的行为,而且具有其他的次要行为。
4、结合1、2点中抽象类和Java接口的各自优势,具精典的设计模式就出来了:声明类型的工作仍然由Java接口承担,但是同时给出一个Java抽象类,且实现了这个接口,而其他同属于这个抽象类型的具体类可以选择实现这个Java接口,也可以选择继承这个抽象类,也就是说在层次结构中,Java接口在最上面,然后紧跟着抽象类,哈,这下两个的最大优点都能发挥到极至了。这个模式就是“缺省适配模式”。
在Java语言API中用了这种模式,而且全都遵循一定的命名规范:Abstract+接口名,Java接口和Java抽象类的存在就是为了用于具体类的实现和继承的,如果你准备写一个具体类去继承另一个具体类的话,那你的设计就有很大问题了。Java抽象类就是为了继承而存在的,它的抽象方法就是为了强制子类必须去实现的。
使用Java接口和抽象Java类进行变量的类型声明、参数是类型声明、方法的返还类型说明,以及数据类型的转换等。而不要用具体Java类进行变量的类型声明、参数是类型声明、方法的返还类型说明,以及数据类型的转换等。
我想,如果你编的代码里面连一个接口和抽象类都没有的话,也许我可以说你根本没有用到任何设计模式,任何一个设计模式都是和抽象分不开的,而抽象与Java接口和抽象Java类又是分不开的。理解抽象,理解Java接口和抽象Java类,我想就应该是真正开始用面向对象的思想去分析问题,解决问题了吧。
Java中int和Integer的区别
int 是基本类型,直接存数值
integer是对象,用一个引用指向这个对象
1.Java 中的数据类型分为基本数据类型和复杂数据类型
int 是前者>>integer 是后者(也就是一个类)
2.初始化时>>
int i =1;
Integer i= new Integer(1);(要把integer 当做一个类看)
int 是基本数据类型(面向过程留下的痕迹,不过是对java的有益补充)
Integer 是一个类,是int的扩展,定义了很多的转换方法
类似的还有:float Float;double Double;string String等
举个例子:当需要往ArrayList,HashMap中放东西时,像int,double这种内建类型是放不进去的,因为容器都是装 object的,这是就需要这些内建类型的外覆类了。
Java中每种内建类型都有相应的外覆类。
Java中int和Integer关系是比较微妙的。关系如下:
1.int是基本的数据类型;
2.Integer是int的封装类;
3.int和Integer都可以表示某一个数值;
4.int和Integer不能够互用,因为他们两种不同的数据类型;
举例说明
Java处理XML服务SOA
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
*
* @author LC
*
*/
public class SumJavaCode {
static long normalLines = 0; // 空行
static long commentLines = 0; // 注释行
static long whiteLines = 0; // 代码行
public static void main(String[] args) {
SumJavaCode sjc = new SumJavaCode();
File f = new File(“D://spring-framework-2.0-with-dependencies//spring-framework-2.0″); //目录
System.out.println(f.getName());
sjc.treeFile(f);
System.out.println(“空行:” + normalLines);
System.out.println(“注释行:” + commentLines);
System.out.println(“代码行:” + whiteLines);
}
/**
* 查找出一个目录下所有的.java文件
*
* @param f 要查找的目录
*/
private void treeFile(File f) {
File[] childs = f.listFiles();
//int count = 0;
//int sum = 0;
for (int i = 0; i < childs.length; i++) {
// System.out.println(preStr + childs[i].getName());
if (!childs[i].isDirectory()) {
if (childs[i].getName().matches(“.*//.java$”)) {
System.out.println(childs[i].getName());
//count ++;
sumCode(childs[i]);
}
} else {
treeFile(childs[i]);
//sum += count;
}
}
}
/**
* 计算一个.java文件中的代码行,空行,注释行
*
* @param file
* 要计算的.java文件
*/
private void sumCode(File file) {
BufferedReader br = null;
boolean comment = false;
try {
br = new BufferedReader(new FileReader(file));
String line = “”;
try {
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.matches(“^[//s&&[^//n]]*$”)) {
whiteLines++;
} else if (line.startsWith(“/*”) && !line.endsWith(“*/”)) {
commentLines++;
comment = true;
} else if (true == comment) {
commentLines++;
if (line.endsWith(“*/”)) {
comment = false;
}
} else if (line.startsWith(“//”)) {
commentLines++;
} else {
normalLines++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
java代码实现行数统计
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
*
* @author LC
*
*/
public class SumJavaCode {
static long normalLines = 0; // 空行
static long commentLines = 0; // 注释行
static long whiteLines = 0; // 代码行
public static void main(String[] args) {
SumJavaCode sjc = new SumJavaCode();
File f = new File(“D://spring-framework-2.0-with-dependencies//spring-framework-2.0″); //目录
System.out.println(f.getName());
sjc.treeFile(f);
System.out.println(“空行:” + normalLines);
System.out.println(“注释行:” + commentLines);
System.out.println(“代码行:” + whiteLines);
}
/**
* 查找出一个目录下所有的.java文件
*
* @param f 要查找的目录
*/
private void treeFile(File f) {
File[] childs = f.listFiles();
//int count = 0;
//int sum = 0;
for (int i = 0; i < childs.length; i++) {
// System.out.println(preStr + childs[i].getName());
if (!childs[i].isDirectory()) {
if (childs[i].getName().matches(“.*//.java$”)) {
System.out.println(childs[i].getName());
//count ++;
sumCode(childs[i]);
}
} else {
treeFile(childs[i]);
//sum += count;
}
}
}
/**
* 计算一个.java文件中的代码行,空行,注释行
*
* @param file
* 要计算的.java文件
*/
private void sumCode(File file) {
BufferedReader br = null;
boolean comment = false;
try {
br = new BufferedReader(new FileReader(file));
String line = “”;
try {
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.matches(“^[//s&&[^//n]]*$”)) {
whiteLines++;
} else if (line.startsWith(“/*”) && !line.endsWith(“*/”)) {
commentLines++;
comment = true;
} else if (true == comment) {
commentLines++;
if (line.endsWith(“*/”)) {
comment = false;
}
} else if (line.startsWith(“//”)) {
commentLines++;
} else {
normalLines++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 默认分类(20)
- J2EE(25)
- Java(56)
- PHP(55)
- SEO(10)
- 网页设计(20)
- 网站建设(37)
- 数据库(7)
- JavaScript(17)
- JQuery(6)
- MySQL(20)
- SQL Server(6)
- Access(1)
- Oracle(6)
- office(6)
- Dreamweaver(4)
- Photoshop(12)
- Flash(9)
- Fireworks(13)
- CSS(14)
- HTML(4)
- .NET(7)
- ASP(2)
- DB2(1)
- Ajax(2)
- Linux(12)
- Struts(7)
- Hibernate(8)
- Spring(2)
- Jsp(22)
- Asp(8)
- C#(3)
- C++(1)
- 网络安全(5)
- 软件工程(7)
- XML(1)
- English(2)
- 计算机等级考试(2)
- 计算机病毒(4)
- 个人日志(76)
- 互联网(15)
- ActionScript(10)
- Android(3)
- 数据结构与算法(1)
- 游戏策略(3)
- 美文翻译(2)
- 编程开发(19)
- 计算机应用(4)
- 计算机(10)
- Unity3d(6)
- 其他(1)
- egret(1)