iLeichun

当前位置:首页Java

Java中日期转换、加减

分类:Java  来源:网络  时间:2010-11-20 14:48:10

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保留两位小数

分类:Java  来源:网络  时间:2010-11-20 14:44:31

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加密

分类:Java  来源:网络  时间:2010-10-28 23:37:06
  1. package cn.org.jshuwei.j2ee.util;
     

  2.  
  3. import java.security.MessageDigest;
     

  4.  
  5. /**
     
  6. *
     
  7. * MD5加密工具类
     
  8. *
     
  9. * @author huwei(jshuwei.org.cn)
     
  10. * @since 1.4
     
  11. *
     
  12. */
     
  13. public class MD5 {
     
  14.         private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
     
  15.                         "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
     

  16.  
  17.         private static String byteArrayToHexString(byte[] bytes) {
     
  18.                 StringBuffer sb = new StringBuffer();
     
  19.                 for (byte b : bytes) {
     
  20.                         sb.append(byteToHexString(b));
     
  21.                 }
     
  22.                 return sb.toString();
     
  23.         }
     

  24.  
  25.         private static String byteToHexString(byte b) {
     
  26.                 int n = b;
     
  27.                 if (n < 0)
     
  28.                         n = 256 + n;
     
  29.                 int d1 = n / 16;
     
  30.                 int d2 = n % 16;
     
  31.                 return hexDigits[d1] + hexDigits[d2];
     
  32.         }
     

  33.  
  34.         /**
     
  35.          * 将字符串加密成MD5字符串
     
  36.          *
     
  37.          * @param origin
     
  38.          *            需要加密的字符串
     
  39.          * @return 加密后的字符串
     
  40.          */
     
  41.         public static String MD5Encode(String origin) {
     
  42.                 String ret = null;
     
  43.                 try {
     
  44.                         ret = new String(origin);
     
  45.                         MessageDigest md = MessageDigest.getInstance("MD5");
     
  46.                         ret = byteArrayToHexString(md.digest(ret.getBytes()));
     
  47.                 } catch (Exception e) {
     
  48.                 }
     
  49.                 return ret;
     
  50.         }
     
  51. }

Java时间处理

分类:Java  来源:网络  时间:2010-10-28 23:34:31

Java时间处理API很丰富,但有时候调用起来不方便。本文代码封装了一些常用的时间处理,方便开发时调用。

  1. package cn.org.jshuwei.j2ee.util;
     

  2.  
  3. import java.sql.Date;
     
  4. import java.text.DateFormat;
     
  5. import java.text.ParseException;
     
  6. import java.text.SimpleDateFormat;
     
  7. import java.util.Calendar;
     

  8.  
  9. /**
     
  10. *
     
  11. * 日期操作的工具类
     
  12. *
     
  13. * @author huwei(jshuwei.org.cn)
     
  14. * @since 1.0
     
  15. *
     
  16. */
     
  17. public class DateUtil {
     

  18.  
  19.         private static String defDtPtn = "yyyy-MM-dd HH:mm:ss";// 缺省日期格式
     

  20.  
  21.         /**
     
  22.          * 计算给定时间至今的天数
     
  23.          *
     
  24.          * @since 1.1
     
  25.          * @param date
     
  26.          *            给定的时间
     
  27.          * @return 给定时间至今的天数
     
  28.          */
     
  29.         public static long date2day(String date) {
     
  30.                 long day = 0;
     
  31.                 DateFormat df = DateFormat.getDateInstance();
     
  32.                 try {
     
  33.                         long old = df.parse(date).getTime();
     
  34.                         long now = new java.util.Date().getTime();
     
  35.                         long secs = now - old;
     
  36.                         day = secs / (1000 * 24 * 60 * 60);
     
  37.                 } catch (ParseException e) {
     
  38.                         e.printStackTrace();
     
  39.                 }
     
  40.                 return day;
     
  41.         }
     

  42.  
  43.         /**
     
  44.          * 格式化给定时间后day天的时间
     
  45.          *
     
  46.          * @since 1.0
     
  47.          * @param date
     
  48.          *            需要格式化的时间
     
  49.          * @param day
     
  50.          *            增加的天数
     
  51.          * @return 给定时间的后day天的格式化字符串(如:2008-11-22)
     
  52.          */
     
  53.         public static String formatDate(java.util.Date date, Integer day) {
     
  54.                 String str = "";
     
  55.                 str = new Date(date.getTime() + day * 24 * 60 * 60).toString();
     
  56.                 return str;
     
  57.         }
     

  58.  
  59.         /**
     
  60.          * 格式化给定时间
     
  61.          *
     
  62.          * @param date
     
  63.          *            需要格式化的时间
     
  64.          * @return 给定时间的格式化字符串(如:2008-11-22)
     
  65.          */
     
  66.         public static String formatDate(java.util.Date date) {
     
  67.                 return new Date(date.getTime()).toString();
     
  68.         }
     

  69.  
  70.         /**
     
  71.          * 得到当前年
     
  72.          *
     
  73.          * @since 1.0
     
  74.          * @return 返回当前年(YYYY)
     
  75.          */
     
  76.         public static int getYear() {
     
  77.                 return Calendar.getInstance().get(Calendar.YEAR);
     
  78.         }
     

  79.  
  80.         /**
     
  81.          * 得到当前月
     
  82.          *
     
  83.          * @since 1.0
     
  84.          * @return 返回当前月(1~12)
     
  85.          */
     
  86.         public static int getMonth() {
     
  87.                 return Calendar.getInstance().get(Calendar.MONTH) + 1;
     
  88.         }
     

  89.  
  90.         /**
     
  91.          * 得到当前日
     
  92.          *
     
  93.          * @since 1.0
     
  94.          * @return 返回当前日(1~31)
     
  95.          */
     
  96.         public static int getDay() {
     
  97.                 return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
     
  98.         }
     

  99.  
  100.         /**
     
  101.          * 得到当前年
     
  102.          *
     
  103.          * @since 1.0
     
  104.          * @return 返回当前年(YY)
     
  105.          */
     
  106.         public static String getYear2() {
     
  107.                 int year = getYear();
     
  108.                 return StringUtil.Integer2String(year, "1986").substring(2, 4);
     
  109.         }
     

  110.  
  111.         /**
     
  112.          * 得到当前月
     
  113.          *
     
  114.          * @since 1.0
     
  115.          * @return 返回当前月(01~12)
     
  116.          */
     
  117.         public static String getMonth2() {
     
  118.                 int month = getMonth();
     
  119.                 if (month < 10) {
     
  120.                         return "0" + StringUtil.Integer2String(month, "00");
     
  121.                 }
     
  122.                 return StringUtil.Integer2String(month, "00");
     
  123.         }
     

  124.  
  125.         /**
     
  126.          * 得到当前日
     
  127.          *
     
  128.          * @since 1.0
     
  129.          * @return 返回当前日(01~31)
     
  130.          */
     
  131.         public static String getDay2() {
     
  132.                 int day = getDay();
     
  133.                 if (day < 10) {
     
  134.                         return "0" + StringUtil.Integer2String(day, "00");
     
  135.                 }
     
  136.                 return StringUtil.Integer2String(day, "00");
     
  137.         }
     

  138.  
  139.         /**
     
  140.          * 得到指定格式的当前时间
     
  141.          *
     
  142.          * @param format
     
  143.          *            格式化形式(年用YY/YYYY表示;月用M/MM表示;日用D/DD表示,之间任意任序组合),<br />
     
  144.          *            如"YYYY-MM-DD"返回形如:1986-12-17<br />
     
  145.          *            如"YY-MM"返回形如:86-12<br />
     
  146.          *            如"YY年MM月"返回形如:86年12月……
     
  147.          * @since 1.0
     
  148.          * @return 返回指定格式的当前时间
     
  149.          *
     
  150.          */
     
  151.         public static String getDate(String format) {
     
  152.                 format = format.replace("YYYY", getYear() + "");
     
  153.                 format = format.replace("YY", getYear2());
     
  154.                 format = format.replace("MM", getMonth2());
     
  155.                 format = format.replace("M", getMonth() + "");
     
  156.                 format = format.replace("DD", getDay2());
     
  157.                 format = format.replace("D", getDay() + "");
     
  158.                 return format;
     
  159.         }
     

  160.  
  161.         /**
     
  162.          * 将字符串按指定格式解析成日期对象
     
  163.          *
     
  164.          * @since 1.1
     
  165.          * @param dateStr
     
  166.          *            需要进行转换的日期字符串
     
  167.          * @param pattern
     
  168.          *            日期字符串的格式
     
  169.          * @return "yyyy-MM-dd HH:mm:ss"形式的日期对象
     
  170.          */
     
  171.         public static java.util.Date parseDate(String dateStr, String pattern) {
     
  172.                 SimpleDateFormat DATEFORMAT = new SimpleDateFormat(defDtPtn);
     
  173.                 DATEFORMAT.applyPattern(pattern);
     
  174.                 java.util.Date ret = null;
     
  175.                 try {
     
  176.                         ret = DATEFORMAT.parse(dateStr);
     
  177.                 } catch (Exception e) {
     
  178.                         e.printStackTrace();
     
  179.                 }
     
  180.                 DATEFORMAT.applyPattern(defDtPtn);
     
  181.                 return ret;
     
  182.         }
     

  183.  
  184.         /**
     
  185.          * 计算详细年龄
     
  186.          *
     
  187.          * @since 1.1
     
  188.          * @param birthdayStr
     
  189.          *            出生日期 格式"YYYY-MM-DD"
     
  190.          * @return 指定日期至今天的年龄
     
  191.          */
     
  192.         public static String countAge(String birthdayStr) {
     
  193.                 String age = "";
     
  194.                 if (birthdayStr != null && birthdayStr.length() == 8) {
     
  195.                         java.util.Date birthday = parseDate(birthdayStr, "YYYY-MM-DD");
     

  196.  
  197.                         if (birthday != null) {
     
  198.                                 Calendar calendar = Calendar.getInstance();
     
  199.                                 int year1 = getYear();
     
  200.                                 int month1 = StringUtil.String2Integer(getMonth2(), 0);
     
  201.                                 int day1 = StringUtil.String2Integer(getDay2(), 00);
     

  202.  
  203.                                 calendar.setTime(birthday);
     
  204.                                 int year2 = calendar.get(Calendar.YEAR);
     
  205.                                 int month2 = calendar.get(Calendar.MONTH) + 1;
     
  206.                                 int day2 = calendar.get(Calendar.DATE);
     

  207.  
  208.                                 int year = year1 - year2;
     
  209.                                 int month = month1 - month2;
     
  210.                                 int day = day1 - day2;
     

  211.  
  212.                                 if (month < 0) {
     
  213.                                         year = year - 1;
     
  214.                                         month = 12 + month1 - month2;
     
  215.                                 }
     

  216.  
  217.                                 if (day < 0) {
     
  218.                                         month = month - 1;
     
  219.                                         if (month < 0) {
     
  220.                                                 year = year - 1;
     
  221.                                                 month = 11;
     
  222.                                         }
     
  223.                                         int lastMonthDay = 0;
     
  224.                                         if (month1 == 0) {
     
  225.                                                 lastMonthDay = getDayOfMonth(12, year1 - 1);
     
  226.                                         } else {
     
  227.                                                 lastMonthDay = getDayOfMonth(month1, year1);
     
  228.                                         }
     
  229.                                         day = lastMonthDay + day1 - day2;
     
  230.                                 }
     

  231.  
  232.                                 if (year > 5) {
     
  233.                                         age = year + "岁";
     
  234.                                 } else if (year > 0) {
     
  235.                                         if (month == 0) {
     
  236.                                                 age = year + "岁";
     
  237.                                         } else {
     
  238.                                                 age = year + "岁" + month + "月";
     
  239.                                         }
     
  240.                                 } else {
     
  241.                                         if (month > 5) {
     
  242.                                                 age = month + "月";
     
  243.                                         } else if (month > 0) {
     
  244.                                                 age = month + "月" + day + "天";
     
  245.                                         } else {
     
  246.                                                 age = day + "天";
     
  247.                                         }
     
  248.                                 }
     
  249.                         }
     
  250.                 }
     

  251.  
  252.                 return age;
     
  253.         }
     

  254.  
  255.         /**
     
  256.          * 得到指定年月的天数
     
  257.          *
     
  258.          * @since 1.1
     
  259.          * @param month
     
  260.          *            指定月份
     
  261.          * @param year
     
  262.          *            指定的年份
     
  263.          * @return 天数
     
  264.          */
     
  265.         public static int getDayOfMonth(int month, int year) {
     
  266.                 int ret = 0;
     
  267.                 boolean flag = false;
     

  268.  
  269.                 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
     
  270.                         flag = true;
     
  271.                 }
     

  272.  
  273.                 switch (month) {
     
  274.                 case 1:
     
  275.                         ret = 31;
     
  276.                         break;
     
  277.                 case 2:
     
  278.                         if (flag) {
     
  279.                                 ret = 29;
     
  280.                         } else {
     
  281.                                 ret = 28;
     
  282.                         }
     
  283.                         break;
     
  284.                 case 3:
     
  285.                         ret = 31;
     
  286.                         break;
     
  287.                 case 4:
     
  288.                         ret = 30;
     
  289.                         break;
     
  290.                 case 5:
     
  291.                         ret = 31;
     
  292.                         break;
     
  293.                 case 6:
     
  294.                         ret = 30;
     
  295.                         break;
     
  296.                 case 7:
     
  297.                         ret = 31;
     
  298.                         break;
     
  299.                 case 8:
     
  300.                         ret = 31;
     
  301.                         break;
     
  302.                 case 9:
     
  303.                         ret = 30;
     
  304.                         break;
     
  305.                 case 10:
     
  306.                         ret = 31;
     
  307.                         break;
     
  308.                 case 11:
     
  309.                         ret = 30;
     
  310.                         break;
     
  311.                 case 12:
     
  312.                         ret = 31;
     
  313.                         break;
     
  314.                 default:
     
  315.                         break;
     
  316.                 }
     
  317.                 return ret;
     
  318.         }
     

  319.  
  320.         /**
     
  321.          * 计算某天是星期几
     
  322.          *
     
  323.          * @since 1.1
     
  324.          * @param p_date
     
  325.          *            日期字符串
     
  326.          * @return 星期
     
  327.          */
     
  328.         public static int whatDayIsSpecifyDate(String p_date) {
     
  329.                 // 2002-2-22 is friday5
     
  330.                 long differenceDays = 0L;
     
  331.                 long m = 0L;
     
  332.                 differenceDays = signDaysBetweenTowDate(p_date, "2002-2-22");
     

  333.  
  334.                 m = (differenceDays % 7);
     
  335.                 m = m + 5;
     
  336.                 m = m > 7 ? m - 7 : m;
     
  337.                 return Integer.parseInt(m + "");
     
  338.         }
     

  339.  
  340.         /**
     
  341.          * 计算两日期间相差天数.
     
  342.          *
     
  343.          * @since 1.1
     
  344.          * @param d1
     
  345.          *            日期字符串
     
  346.          * @param d2
     
  347.          *            日期字符串
     
  348.          * @return long 天数
     
  349.          */
     
  350.         public static long signDaysBetweenTowDate(String d1, String d2) {
     
  351.                 java.sql.Date dd1 = null;
     
  352.                 java.sql.Date dd2 = null;
     
  353.                 long result = -1l;
     
  354.                 try {
     
  355.                         dd1 = java.sql.Date.valueOf(d1);
     
  356.                         dd2 = java.sql.Date.valueOf(d2);
     
  357.                         result = signDaysBetweenTowDate(dd1, dd2);
     
  358.                 } catch (Exception ex) {
     
  359.                         result = -1;
     
  360.                 }
     
  361.                 return result;
     
  362.         }
     

  363.  
  364.         /**
     
  365.          * 计算两日期间相差天数.
     
  366.          *
     
  367.          * @since 1.1
     
  368.          * @param d1
     
  369.          *            开始日期 日期型
     
  370.          * @param d2
     
  371.          *            结束日期 日期型
     
  372.          * @return long 天数
     
  373.          */
     
  374.         public static long signDaysBetweenTowDate(java.sql.Date d1, java.sql.Date d2) {
     
  375.                 return (d1.getTime() - d2.getTime()) / (3600 * 24 * 1000);
     
  376.         }
     
  377. }

Java数组操作

分类:Java  来源:网络  时间:2010-10-28 23:33:07
  1. package cn.org.jshuwei.j2ee.util;
     

  2.  
  3. /**
     
  4. *
     
  5. * 数组操作的工具类(以int型数组为例)
     
  6. *
     
  7. * <b>排序算法的分类如下:</b><br /> 1.插入排序(直接插入排序、折半插入排序、希尔排序); <br />
     
  8. * 2.交换排序(冒泡泡排序、快速排序);<br /> 3.选择排序(直接选择排序、堆排序);<br /> 4.归并排序; <br /> 5.基数排序。<br
     
  9. * />
     
  10. *
     
  11. * <b>关于排序方法的选择:</b><br /> (1)若n较小(如n≤50),可采用直接插入或直接选择排序。<br />
     
  12. * (2)若文件初始状态基本有序(指正序),则应选用直接插人、冒泡或随机的快速排序为宜;<br />
     
  13. * (3)若n较大,则应采用时间复杂度为O(nlgn)的排序方法:快速排序、堆排序或归并排序。<br />
     
  14. *
     
  15. * @author huwei(jshuwei.org.cn)
     
  16. * @since 1.1
     
  17. *
     
  18. */
     
  19. public class ArrayUtil {
     
  20.         /**
     
  21.          * 交换数组中两元素
     
  22.          *
     
  23.          * @since 1.1
     
  24.          * @param ints
     
  25.          *            需要进行交换操作的数组
     
  26.          * @param x
     
  27.          *            数组中的位置1
     
  28.          * @param y
     
  29.          *            数组中的位置2
     
  30.          * @return 交换后的数组
     
  31.          */
     
  32.         public static int[] swap(int[] ints, int x, int y) {
     
  33.                 int temp = ints[x];
     
  34.                 ints[x] = ints[y];
     
  35.                 ints[y] = temp;
     
  36.                 return ints;
     
  37.         }
     

  38.  
  39.         /**
     
  40.          * 冒泡排序 方法:相邻两元素进行比较 性能:比较次数O(n^2),n^2/2;交换次数O(n^2),n^2/4
     
  41.          *
     
  42.          * @since 1.1
     
  43.          * @param source
     
  44.          *            需要进行排序操作的数组
     
  45.          * @return 排序后的数组
     
  46.          */
     
  47.         public static int[] bubbleSort(int[] source) {
     
  48.                 for (int i = 1; i < source.length; i++) {
     
  49.                         for (int j = 0; j < i; j++) {
     
  50.                                 if (source[j] > source[j + 1]) {
     
  51.                                         swap(source, j, j + 1);
     
  52.                                 }
     
  53.                         }
     
  54.                 }
     
  55.                 return source;
     
  56.         }
     

  57.  
  58.         /**
     
  59.          * 直接选择排序法 方法:每一趟从待排序的数据元素中选出最小(或最大)的一个元素, 顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
     
  60.          * 性能:比较次数O(n^2),n^2/2 交换次数O(n),n
     
  61.          * 交换次数比冒泡排序少多了,由于交换所需CPU时间比比较所需的CUP时间多,所以选择排序比冒泡排序快。
     
  62.          * 但是N比较大时,比较所需的CPU时间占主要地位,所以这时的性能和冒泡排序差不太多,但毫无疑问肯定要快些。
     
  63.          *
     
  64.          * @since 1.1
     
  65.          * @param source
     
  66.          *            需要进行排序操作的数组
     
  67.          * @return 排序后的数组
     
  68.          */
     
  69.         public static int[] selectSort(int[] source) {
     

  70.  
  71.                 for (int i = 0; i < source.length; i++) {
     
  72.                         for (int j = i + 1; j < source.length; j++) {
     
  73.                                 if (source[i] > source[j]) {
     
  74.                                         swap(source, i, j);
     
  75.                                 }
     
  76.                         }
     
  77.                 }
     
  78.                 return source;
     
  79.         }
     

  80.  
  81.         /**
     
  82.          * 插入排序 方法:将一个记录插入到已排好序的有序表(有可能是空表)中,从而得到一个新的记录数增1的有序表。 性能:比较次数O(n^2),n^2/4
     
  83.          * 复制次数O(n),n^2/4 比较次数是前两者的一般,而复制所需的CPU时间较交换少,所以性能上比冒泡排序提高一倍多,而比选择排序也要快。
     
  84.          *
     
  85.          * @since 1.1
     
  86.          * @param source
     
  87.          *            需要进行排序操作的数组
     
  88.          * @return 排序后的数组
     
  89.          */
     
  90.         public static int[] insertSort(int[] source) {
     

  91.  
  92.                 for (int i = 1; i < source.length; i++) {
     
  93.                         for (int j = i; (j > 0) && (source[j] < source[j - 1]); j--) {
     
  94.                                 swap(source, j, j - 1);
     
  95.                         }
     
  96.                 }
     
  97.                 return source;
     
  98.         }
     

  99.  
  100.         /**
     
  101.          * 快速排序 快速排序使用分治法(Divide and conquer)策略来把一个序列(list)分为两个子序列(sub-lists)。 步骤为:
     
  102.          * 1. 从数列中挑出一个元素,称为 "基准"(pivot), 2.
     
  103.          * 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面
     
  104.          * (相同的数可以到任一边)。在这个分割之后,该基准是它的最后位置。这个称为分割(partition)操作。 3.
     
  105.          * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
     
  106.          * 递回的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了
     
  107.          * 。虽然一直递回下去,但是这个算法总会结束,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。
     
  108.          *
     
  109.          * @since 1.1
     
  110.          * @param source
     
  111.          *            需要进行排序操作的数组
     
  112.          * @return 排序后的数组
     
  113.          */
     
  114.         public static int[] quickSort(int[] source) {
     
  115.                 return qsort(source, 0, source.length - 1);
     
  116.         }
     

  117.  
  118.         /**
     
  119.          * 快速排序的具体实现,排正序
     
  120.          *
     
  121.          * @since 1.1
     
  122.          * @param source
     
  123.          *            需要进行排序操作的数组
     
  124.          * @param low
     
  125.          *            开始低位
     
  126.          * @param high
     
  127.          *            结束高位
     
  128.          * @return 排序后的数组
     
  129.          */
     
  130.         private static int[] qsort(int source[], int low, int high) {
     
  131.                 int i, j, x;
     
  132.                 if (low < high) {
     
  133.                         i = low;
     
  134.                         j = high;
     
  135.                         x = source[i];
     
  136.                         while (i < j) {
     
  137.                                 while (i < j && source[j] > x) {
     
  138.                                         j--;
     
  139.                                 }
     
  140.                                 if (i < j) {
     
  141.                                         source[i] = source[j];
     
  142.                                         i++;
     
  143.                                 }
     
  144.                                 while (i < j && source[i] < x) {
     
  145.                                         i++;
     
  146.                                 }
     
  147.                                 if (i < j) {
     
  148.                                         source[j] = source[i];
     
  149.                                         j--;
     
  150.                                 }
     
  151.                         }
     
  152.                         source[i] = x;
     
  153.                         qsort(source, low, i - 1);
     
  154.                         qsort(source, i + 1, high);
     
  155.                 }
     
  156.                 return source;
     
  157.         }
     

  158.  
  159.         /**
     
  160.          * 二分法查找 查找线性表必须是有序列表
     
  161.          *
     
  162.          * @since 1.1
     
  163.          * @param source
     
  164.          *            需要进行查找操作的数组
     
  165.          * @param key
     
  166.          *            需要查找的值
     
  167.          * @return 需要查找的值在数组中的位置,若未查到则返回-1
     
  168.          */
     
  169.         public int binarySearch(int[] source, int key) {
     
  170.                 int low = 0, high = source.length - 1, mid;
     
  171.                 while (low <= high) {
     
  172.                         mid = (low + high) >>> 1;
     
  173.                         if (key == source[mid]) {
     
  174.                                 return mid;
     
  175.                         } else if (key < source[mid]) {
     
  176.                                 high = mid - 1;
     
  177.                         } else {
     
  178.                                 low = mid + 1;
     
  179.                         }
     
  180.                 }
     
  181.                 return -1;
     
  182.         }
     

  183.  
  184.         /**
     
  185.          * 反转数组
     
  186.          *
     
  187.          * @since 1.1
     
  188.          * @param source
     
  189.          *            需要进行反转操作的数组
     
  190.          * @return 反转后的数组
     
  191.          */
     
  192.         public static int[] reverse(int[] source) {
     
  193.                 int length = source.length;
     
  194.                 int temp = 0;
     
  195.                 for (int i = 0; i < length / 2; i++) {
     
  196.                         temp = source[i];
     
  197.                         source[i] = source[length - 1 - i];
     
  198.                         source[length - 1 - i] = temp;
     
  199.                 }
     
  200.                 return source;
     
  201.         }
     
  202. }

Java Applet

分类:Java  来源:网络  时间:2010-10-28 23:25:01

  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  来源:网络  时间:2010-10-28 23:18:31

  在没有好好地研习面向对象设计的设计模式之前,我对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的区别

分类:Java  来源:网络  时间:2010-10-28 23:14:32

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

分类:Java  来源:网络  时间:2010-10-28 23:13:32

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代码实现行数统计

分类:Java  来源:网络  时间:2010-10-28 23:11:26

        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();
  }
  }
  }
  }
  }