Java 实例
本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用。
Java 环境设置实例
-
//HelloWorld.java 文件 public class HelloWorld { public static void main(String []args) { System.out.println("Hello World"); } } /* 接下来我们使用 javac 命令来编译 Java 文件,并使用 java 命令执行编译的文件: c:\jdk\demoapp> javac HelloWorld.java c:\jdk\demoapp> java HelloWorld 以上代码实例输出结果为: Hello World */
-
//HelloWorld.java 文件 public class HelloWorld { public static void main(String []args) { System.out.println("Hello World"); } } /*接下来我们使用 javac 命令来编译 Java 文件,执行该命令后在当前目录下会生成一个 HelloWorld.class 文件,我们可以使用 java 命令执行编译的文件: c:\jdk\demoapp> javac HelloWorld.java c:\jdk\demoapp> java HelloWorld 以上代码实例输出结果为: Hello World */
/* 如果我们 Java 编译后的class文件不在当前目录,我们可以使用 -classpath 来指定class文件目录:*/ C:> java -classpath C:\java\DemoClasses HelloWorld /* 以上命令中我们使用了 -classpath 参数指定了 HelloWorld 的 class 文件所在目录。 如果class文件在jar文件中,则命令如下:*/ c:> java -classpath C:\java\myclasses.jar
//我们可以使用 -version 参数来查看当前 Java 的运行版本,命令如下: java -version //以上代码实例输出结果为: java version "1.6.0_13" Java(TM) SE Runtime Environment (build 1.6.0_13-b03) Java HotSpot(TM) Client VM (build 11.3-b02, mixed mode, sharing)
Java 字符串
- Java 实例 – 字符串比较
以下实例中我们通过字符串函数 compareTo (string) ,compareToIgnoreCase(String) 及 compareTo(object string) 来比较两个字符串,并返回字符串中第一个字母ASCII的差值。
/* 实例代码如下: * StringCompareEmp.java 文件 */ public class StringCompareEmp{ public static void main(String args[]){ String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; System.out.println( str.compareTo(anotherString) ); System.out.println( str.compareToIgnoreCase(anotherString) ); //忽略大小写 System.out.println( str.compareTo(objStr.toString())); } } /* 以上代码实例输出结果为: -32 */
- Java 实例 - 查找字符串最后一次出现的位置
/* 以下实例中我们通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置: 实例代码如下: SearchlastString.java 文件 */ public class SearchlastString { public static void main(String[] args) { String strOrig = "Hello world ,Hello Runoob"; int lastIndex = strOrig.lastIndexOf("Runoob"); if(lastIndex == - 1){ System.out.println("没有找到字符串 Runoob"); }else{ System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex); } } } /* 以上代码实例输出结果为: Runoob 字符串最后出现的位置: 19 */
- Java 实例 - 删除字符串中的一个字符
/* 以下实例中我们通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。 实例代码如下: Main.java 文件 */ public class Main { public static void main(String args[]) { String str = "this is Java"; System.out.println(removeCharAt(str, 3)); } public static String removeCharAt(String s, int pos) { return s.substring(0, pos) + s.substring(pos + 1); } } /* 以上代码实例输出结果为: thi is Java */
- Java 实例 - 字符串替换
/* 如何使用java替换字符串中的字符呢? 以下实例中我们使用 java String 类的 replace 方法来替换字符串中的字符: StringReplaceEmp.java 文件 */ public class StringReplaceEmp{ public static void main(String args[]){ String str="Hello World"; System.out.println( str.replace( 'H','W' ) ); System.out.println( str.replaceFirst("He", "Wa") ); System.out.println( str.replaceAll("He", "Ha") ); } } /* 以上代码实例输出结果为: Wello World Wallo World Hallo World */
- Java 实例 - 字符串反转
/* 以下实例演示了如何使用 Java 的反转函数 reverse() 将字符串反转: StringReverseExample.java 文件 */ public class StringReverseExample{ public static void main(String[] args){ String string="runoob"; String reverse = new StringBuffer(string).reverse().toString(); System.out.println("字符串反转前:"+string); System.out.println("字符串反转后:"+reverse); } } /* 以上代码实例输出结果为: 字符串反转前:runoob 字符串反转后:boonur */
- Java 实例 - 字符串查找
/* 以下实例使用了 String 类的 indexOf() 方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置(第一位为0),如果不存在返回 -1: SearchStringEmp.java 文件 */ public class SearchStringEmp { public static void main(String[] args) { String strOrig = "Google Runoob Taobao"; int intIndex = strOrig.indexOf("Runoob"); if(intIndex == - 1){ System.out.println("没有找到字符串 Runoob"); }else{ System.out.println("Runoob 字符串位置 " + intIndex); } } } /* 以上代码实例输出结果为: Runoob 字符串位置 7 */
- Java 实例 - 字符串分割
/* 以下实例使用了 split(string) 方法通过指定分隔符将字符串分割为数组: JavaStringSplitEmp.java 文件 */ public class JavaStringSplitEmp { public static void main(String args[]){ String str = "www-runoob-com"; String[] temp; String delimeter = "-"; // 指定分割字符 temp = str.split(delimeter); // 分割字符串 // 普通 for 循环 for(int i =0; i < temp.length ; i++){ System.out.println(temp[i]); System.out.println(""); } System.out.println("------java for each循环输出的方法-----"); String str1 = "www.runoob.com"; String[] temp1; String delimeter1 = "\\."; // 指定分割字符, . 号需要转义 temp1 = str1.split(delimeter1); // 分割字符串 for(String x : temp1){ System.out.println(x); System.out.println(""); } } } /* 以上代码实例输出结果为: www runoob com ------java for each循环输出的方法----- www runoob com */
- Java 实例 - 字符串小写转大写
/** 以下实例使用了 String toUpperCase() 方法将字符串从小写转为大写: StringToUpperCaseEmp.java 文件 */ public class StringToUpperCaseEmp { public static void main(String[] args) { String str = "string runoob"; String strUpper = str.toUpperCase(); System.out.println("原始字符串: " + str); System.out.println("转换为大写: " + strUpper); } } /* 以上代码实例输出结果为: 原始字符串: string runoob 转换为大写: STRING RUNOOB */
- Java 实例 - 测试两个字符串区域是否相等
/** 以下实例使用了 regionMatches() 方法测试两个字符串区域是否相等: StringRegionMatch.java 文件 */ public class StringRegionMatch{ public static void main(String[] args){ String first_str = "Welcome to Microsoft"; String second_str = "I work with microsoft"; boolean match1 = first_str. regionMatches(11, second_str, 12, 9); boolean match2 = first_str. regionMatches(true, 11, second_str, 12, 9); //第一个参数 true 表示忽略大小写区别 System.out.println("区分大小写返回值:" + match1); System.out.println("不区分大小写返回值:" + match2); } } /* first_str.regionMatches(11, second_str, 12, 9) 表示将 first_str 字符串从第11个字符"M"开始和 second_str 字符串的第12个字符"M"开始逐个比较,共比较 9 对字符,由于字符串区分大小写,所以结果为false。 如果设置第一个参数为 true ,则表示忽略大小写区别,所以返回 true。 以上代码实例输出结果为: 区分大小写返回值:false 不区分大小写返回值:true */
- Java 实例 - 字符串性能比较测试(String 创建 和 new String 对象创建 对比)
/* 以下实例演示了通过两种方式创建字符串,并测试其性能: StringComparePerformance.java 文件 */ public class StringComparePerformance{ public static void main(String[] args){ long startTime = System.currentTimeMillis(); for(int i=0;i<50000;i++){ String s1 = "hello"; String s2 = "hello"; } long endTime = System.currentTimeMillis(); System.out.println("通过 String 关键词创建字符串" + " : "+ (endTime - startTime) + " 毫秒" ); long startTime1 = System.currentTimeMillis(); for(int i=0;i<50000;i++){ String s3 = new String("hello"); String s4 = new String("hello"); } long endTime1 = System.currentTimeMillis(); System.out.println("通过 String 对象创建字符串" + " : " + (endTime1 - startTime1) + " 毫秒"); } } /* 以上代码实例输出结果为: 通过 String 关键词创建字符串 : 6 毫秒 通过 String 对象创建字符串 : 14 毫秒 */
- Java 实例 - 字符串优化
/* 以下实例演示了通过 String.intern() 方法来优化字符串: StringOptimization.java 文件 */ public class StringOptimization { public static void main(String[] args){ String variables[] = new String[50000]; for( int i=0;i <50000;i++){ variables[i] = "s"+i; } long startTime0 = System.currentTimeMillis(); for(int i=0;i<50000;i++){ variables[i] = "hello"; } long endTime0 = System.currentTimeMillis(); System.out.println("直接使用字符串: "+ (endTime0 - startTime0) + " ms" ); long startTime1 = System.currentTimeMillis(); for(int i=0;i<50000;i++){ variables[i] = new String("hello"); } long endTime1 = System.currentTimeMillis(); System.out.println("使用 new 关键字:" + (endTime1 - startTime1) + " ms"); long startTime2 = System.currentTimeMillis(); for(int i=0;i<50000;i++){ variables[i] = new String("hello"); variables[i] = variables[i].intern(); } long endTime2 = System.currentTimeMillis(); System.out.println("使用字符串对象的 intern() 方法: " + (endTime2 - startTime2) + " ms"); } } /* 以上代码实例输出结果为: 直接使用字符串: 3 ms 使用 new 关键字:5 ms 使用字符串对象的 intern() 方法: 10 ms */
- Java 实例 - 字符串格式化
/* 以下实例演示了通过 format() 方法来格式化字符串,还可以指定地区来格式化: StringFormat.java 文件 */ import java.util.*; public class StringFormat { public static void main(String[] args){ double e = Math.E; System.out.format("%f%n", e); System.out.format(Locale.CHINA , "%-10.4f%n%n", e); //指定本地为中国(CHINA) } } /* 以上代码实例输出结果为: 2.718282 2.7183 */
- Java 实例 - 连接字符串
/* 以下实例演示了通过 "+" 操作符和StringBuffer.append() 方法来连接字符串,并比较其性能: StringConcatenate.java 文件 */ public class StringConcatenate { public static void main(String[] args){ long startTime = System.currentTimeMillis(); for(int i=0;i<5000;i++){ String result = "This is" + "testing the" + "difference"+ "between" + "String"+ "and"+ "StringBuffer"; } long endTime = System.currentTimeMillis(); System.out.println("字符串连接" + " - 使用 + 操作符 : " + (endTime - startTime)+ " ms"); long startTime1 = System.currentTimeMillis(); for(int i=0;i<5000;i++){ StringBuffer result = new StringBuffer(); result.append("This is"); result.append("testing the"); result.append("difference"); result.append("between"); result.append("String"); result.append("and"); result.append("StringBuffer"); } long endTime1 = System.currentTimeMillis(); System.out.println("字符串连接" + " - 使用 StringBuffer : " + (endTime1 - startTime1)+ " ms"); } } /* 以上代码实例输出结果为: 字符串连接 - 使用 + 操作符 : 0 ms 字符串连接 - 使用 StringBuffer : 6 ms */
Java 数组
- Java 实例 – 数组排序及元素查找
以下实例演示了如何使用sort()方法对Java数组进行排序,及如何使用 binarySearch() 方法来查找数组中的元素, 这边我们定义了 printArray() 方法来打印数组:
public static int binarySearch(int[] a, int key): 使用二进制搜索算法来搜索指定的 int 型数组,以获得指定的值。必须在进行此调用之前对数组进行排序(通过上面的 sort 方法)。如果没有对数组进行排序,则结果是不明确的。如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。
/* MainClass.java 文件 */ import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(array); printArray("数组排序结果为", array); int index = Arrays.binarySearch(array, 2); System.out.println("元素 2 在第 " + index + " 个位置"); } private static void printArray(String message, int array[]) { System.out.println(message + ": [length: " + array.length + "]"); for (int i = 0; i < array.length; i++) { if(i != 0){ System.out.print(", "); } System.out.print(array[i]); } System.out.println(); } } /* 以上代码运行输出结果为: 数组排序结果为: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 元素 2 在第 5 个位置 */
- Java 实例 – 数组添加元素
以下实例演示了如何使用sort()方法对Java数组进行排序,及如何使用 insertElement () 方法向数组插入元素, 这边我们定义了 printArray() 方法来打印数组:
其中用到 复制数组方法:public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
src:源数组;
srcPos:源数组要复制的起始位置;
dest:目的数组;
destPos:目的数组放置的起始位置;
length:复制的长度。
注意:src and dest 都必须是同类型或者可以进行转换类型的数组. 有趣的是这个函数可以实现自己到自己复制,比如: int[] fun ={0,1,2,3,4,5,6}; System.arraycopy(fun,0,fun,3,3); 则结果为:{0,1,2,0,1,2,6}; 实现过程是这样的,先生成一个长度为length的临时数组,将fun数组中srcPos 到srcPos+length-1之间的数据拷贝到临时数组中,再执行System.arraycopy(临时数组,0,fun,3,3)./* MainClass.java 文件 */ import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(array); printArray("数组排序", array); int index = Arrays.binarySearch(array, 1); System.out.println("元素 1 所在位置(负数为不存在):" + index); int newIndex = -index - 1; array = insertElement(array, 1, newIndex); printArray("数组添加元素 1", array); } private static void printArray(String message, int array[]) { System.out.println(message + ": [length: " + array.length + "]"); for (int i = 0; i < array.length; i++) { if (i != 0){ System.out.print(", "); } System.out.print(array[i]); } System.out.println(); } private static int[] insertElement(int original[], int element, int index) { int length = original.length; int destination[] = new int[length + 1]; System.arraycopy(original, 0, destination, 0, index); destination[index] = element; System.arraycopy(original, index, destination, index + 1, length - index); return destination; } } /* 以上代码运行输出结果为: 数组排序: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 元素 1 所在位置(负数为不存在):-6 数组添加元素 1: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8 */
- Java 实例 – 获取数组长度
/* 本文我们将为大家介绍如何使用数组的属性 length 来获取数组的长度。 * 以下实例中我们定义了二维数组,并获取数组的长度: * Main.java 文件 */ public class Main { public static void main(String args[]) { String[][] data = new String[2][5]; System.out.println("第一维数组长度: " + data.length); System.out.println("第二维数组长度: " + data[0].length); } } /* 以上代码运行输出结果为: 第一维数组长度: 2 第二维数组长度: 5 */
- Java 实例 – 数组反转:
使用 Collections.reverse(ArrayList) 将数组进行反转:
/* 以下实例中我们使用 Collections.reverse(ArrayList) 将数组进行反转: * Main.java 文件 */ import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); arrayList.add("D"); arrayList.add("E"); System.out.println("反转前排序: " + arrayList); Collections.reverse(arrayList); System.out.println("反转后排序: " + arrayList); } } /* 以上代码运行输出结果为: 反转前排序: [A, B, C, D, E] 反转后排序: [E, D, C, B, A] */
- Java 实例 – 数组输出
/* 以下实例演示了如何通过循环输出数组: Welcome.java 文件 */ public class Welcome { public static void main(String[] args){ String[] greeting = new String[3]; greeting[0] = "菜鸟教程"; greeting[1] = "菜鸟工具"; greeting[2] = "菜鸟笔记"; for (int i = 0; i < greeting.length; i++){ System.out.println(greeting[i]); } } } /* 以上代码运行输出结果为: 菜鸟教程 菜鸟工具 菜鸟笔记 */
- Java 实例 – 数组获取最大和最小值: Arrays.asList(arr): 遍历数组
/* 以下实例演示了如何通过 Collection 类的 Collection.max() 和 Collection.min() 方法来查找数组中的最大和最小值: * Main.java 文件 */ import java.util.Arrays; import java.util.Collections; public class Main { public static void main(String[] args) { Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5}; int min = (int) Collections.min(Arrays.asList(numbers)); int max = (int) Collections.max(Arrays.asList(numbers)); System.out.println("最小值: " + min); System.out.println("最大值: " + max); } } /* 以上代码运行输出结果为: 最小值: 1 最大值: 9 */
- Java 实例 – 数组合并
/* 以下实例演示了如何通过 List 类的 Arrays.toString () 方法和 List 类的 list.Addall(array1.asList(array2) 方法将两个数组合并为一个数组: Main.java 文件 */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String args[]) { String a[] = { "A", "E", "I" }; String b[] = { "O", "U" }; List list = new ArrayList(Arrays.asList(a)); list.addAll(Arrays.asList(b)); Object[] c = list.toArray(); System.out.println(Arrays.toString(c)); } } /* 以上代码运行输出结果为: [A, E, I, O, U] */
- Java 实例 – 数组填充
通过 Java Util 类的 Array.fill(arrayname,value) 方法和 Array.fill(arrayname ,starting index ,ending index ,value) 方法向数组中填充元素:
/* Main.java 文件 */ import java.util.*; public class FillTest { public static void main(String args[]) { int array[] = new int[6]; Arrays.fill(array, 100); for (int i=0, n=array.length; i < n; i++) { System.out.println(array[i]); } System.out.println(); Arrays.fill(array, 3, 6, 50); for (int i=0, n=array.length; i< n; i++) { System.out.println(array[i]); } } } /* 以上代码运行输出结果为: 100 100 100 100 100 100 100 100 100 50 50 50 */
- Java 实例 – 数组扩容
/* 以下实例演示了如何在数组初始化后对数组进行扩容: Main.java 文件 */ public class Main { public static void main(String[] args) { String[] names = new String[] { "A", "B", "C" }; String[] extended = new String[5]; extended[3] = "D"; extended[4] = "E"; System.arraycopy(names, 0, extended, 0, names.length); for (String str : extended){ System.out.println(str); } } } /* 以上代码运行输出结果为: A B C D E */
- Java 实例 – 数组排序及查找
/* 以下实例演示了如何使用 sort () 和 binarySearch () 方法来对数组进行排序及查找数组中的元素,我们定义了 printArray() 输出结果: Main.java 文件 */ import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(array); printArray("Sorted array", array); int index = Arrays.binarySearch(array, 2); System.out.println("Found 2 @ " + index); } private static void printArray(String message, int array[]) { System.out.println(message + ": [length: " + array.length + "]"); for (int i = 0; i < array.length; i++) { if(i != 0){ System.out.print(", "); } System.out.print(array[i]); } System.out.println(); } } /* 以上代码运行输出结果为: Sorted array: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 Found 2 @ 5 */
- Java 实例 – 删除数组元素
/* 以下实例演示了如何使用 remove () 方法来删除数组元素: Main.java 文件 */ import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList objArray = new ArrayList(); objArray.clear(); objArray.add(0,"第 0 个元素"); objArray.add(1,"第 1 个元素"); objArray.add(2,"第 2 个元素"); System.out.println("数组删除元素前:"+objArray); objArray.remove(1); objArray.remove("0th element"); System.out.println("数组删除元素后:"+objArray); } } /* 以上代码运行输出结果为: 数组删除元素前:[第 0 个元素, 第 1 个元素, 第 2 个元素] 数组删除元素后:[第 0 个元素, 第 2 个元素] */
- Java 实例 – 数组差集
/* 以下实例演示了如何使用 removeAll () 方法来计算两个数组的差集: * Main.java 文件 */ import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList(); objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon"); objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); objArray.add(2,"notcommon2"); System.out.println("array1 的元素" +objArray); System.out.println("array2 的元素" +objArray2); objArray.removeAll(objArray2); System.out.println("array1 与 array2 数组差集为:"+objArray); } } /* 以上代码运行输出结果为: array1 的元素[common1, common2, notcommon2] array2 的元素[common1, common2, notcommon, notcommon1] array1 与 array2 数组差集为:[notcommon2] */
- Java 实例 – 数组交集
/* 以下实例演示了如何使用 retainAll () 方法来计算两个数组的交集: * Main.java 文件 */ import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList(); objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon"); objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); objArray.add(2,"notcommon2"); System.out.println("array1 数组元素:"+objArray); System.out.println("array2 数组元素:"+objArray2); objArray.retainAll(objArray2); System.out.println("array2 & array1 数组交集为:"+objArray); } } /* 以上代码运行输出结果为: array1 数组元素:[common1, common2, notcommon2] array2 数组元素:[common1, common2, notcommon, notcommon1] array2 & array1 数组交集为:[common1, common2] */
- Java 实例 – 在数组中查找指定元素
/* 以下实例演示了如何使用 contains () 方法来查找数组中的指定元素: * Main.java 文件 */ import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList(); objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon"); objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); System.out.println("objArray 的数组元素:"+objArray); System.out.println("objArray2 的数组元素:"+objArray2); System.out.println("objArray 是否包含字符串common2? : " +objArray.contains("common1")); System.out.println("objArray2 是否包含数组 objArray? :" +objArray2.contains(objArray) ); } } /* 以上代码运行输出结果为: objArray 的数组元素:[common1, common2] objArray2 的数组元素:[common1, common2, notcommon, notcommon1] objArray 是否包含字符串common2? : true objArray2 是否包含数组 objArray? :false */
- Java 实例 – 判断数组是否相等
/* 以下实例演示了如何使用 equals ()方法来判断数组是否相等: * Main.java 文件 */ import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { int[] ary = {1,2,3,4,5,6}; int[] ary1 = {1,2,3,4,5,6}; int[] ary2 = {1,2,3,4}; System.out.println("数组 ary 是否与数组 ary1相等? :" +Arrays.equals(ary, ary1)); System.out.println("数组 ary 是否与数组 ary2相等? :" +Arrays.equals(ary, ary2)); } } /* 以上代码运行输出结果为: 数组 ary 是否与数组 ary1相等? :true 数组 ary 是否与数组 ary2相等? :false */
- Java 实例 - 数组并集
/* 以下实例演示了如何使用 union ()方法来计算两个数组的并集: * Main.java 文件 */ import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) throws Exception { String[] arr1 = { "1", "2", "3" }; String[] arr2 = { "4", "5", "6" }; String[] result_union = union(arr1, arr2); System.out.println("并集的结果如下:"); for (String str : result_union) { System.out.println(str); } } // 求两个字符串数组的并集,利用set的元素唯一性 public static String[] union(String[] arr1, String[] arr2) { Set<String> set = new HashSet<String>(); for (String str : arr1) { set.add(str); } for (String str : arr2) { set.add(str); } String[] result = { }; return set.toArray(result); } } /* 以上代码运行输出结果为: 并集的结果如下: 1 2 3 4 5 6 */
Java 时间处理
- Java 实例 - 格式化时间(SimpleDateFormat)
/* 以下实例演示了如何使用 SimpleDateFormat 类的 format(date) 方法来格式化时间 * Main.java 文件 */ import java.text.SimpleDateFormat; import java.util.Date; public class Main{ public static void main(String[] args){ Date date = new Date(); String strDateFormat = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); System.out.println(sdf.format(date)); } } /* 以上代码运行输出结果为: 2015-03-27 21:13:23 */
- Java 实例 - 获取当前时间
/* 以下实例演示了如何使用 Date 类及 SimpleDateFormat 类的 format(date) 方法来输出当前时间: * Main.java 文件 */ import java.text.SimpleDateFormat; import java.util.Date; public class Main{ public static void main(String[] args){ SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间 sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记 Date date = new Date();// 获取当前时间 System.out.println("现在时间:" + sdf.format(date)); // 输出已经格式化的现在时间(24小时制) } } /* 以上代码运行输出结果为: 现在时间:2015-03-27 21:27:28 下午 */
- Java 实例 - 获取年份、月份等
/* 以下实例演示了如何使用 Calendar 类来输出年份、月份等: * Main.java 文件 */ import java.util.Calendar; public class Main { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DATE); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); int dow = cal.get(Calendar.DAY_OF_WEEK); int dom = cal.get(Calendar.DAY_OF_MONTH); int doy = cal.get(Calendar.DAY_OF_YEAR); System.out.println("当期时间: " + cal.getTime()); System.out.println("日期: " + day); System.out.println("月份: " + month); System.out.println("年份: " + year); System.out.println("一周的第几天: " + dow); // 星期日为一周的第一天输出为 1,星期一输出为 2,以此类推 System.out.println("一月中的第几天: " + dom); System.out.println("一年的第几天: " + doy); } } /* 以上代码运行输出结果为: 当期时间: Fri Mar 27 21:44:15 CST 2015 日期: 27 月份: 3 年份: 2015 一周的第几天: 6 一月中的第几天: 27 一年的第几天: 86 */
- Java 实例 - 时间戳转换成时间
/* 以下实例演示了如何使用 SimpleDateFormat 类的 format() 方法将时间戳转换成时间: * Main.java 文件 */ import java.text.SimpleDateFormat; import java.util.Date; public class Main{ public static void main(String[] args){ Long timeStamp = System.currentTimeMillis(); //获取当前时间戳 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp)))); // 时间戳转换成时间 System.out.println(sd); } } /* 以上代码运行输出结果为: 2015-03-28 */
Java 方法
- Java 实例 – 方法重载
先来看下方法重载(Overloading)的定义:如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。具体说明如下:
- 方法名相同
- 方法的参数类型,个数顺序至少有一项不同
- 方法的返回类型可以不相同
- 方法的修饰符可以不相同
- main方法也可以被重载
以下实例演示了如何重载 MyClass 类的 info 方法:
/* MainClass.java 文件 */ class MyClass { int height; MyClass() { System.out.println("无参数构造函数"); height = 4; } MyClass(int i) { System.out.println("房子高度为 " + i + " 米"); height = i; } void info() { System.out.println("房子高度为 " + height + " 米"); } void info(String s) { System.out.println(s + ": 房子高度为 " + height + " 米"); } } public class MainClass { public static void main(String[] args) { MyClass t = new MyClass(3); t.info(); t.info("重载方法"); //重载构造函数 new MyClass(); } } /* 以上代码运行输出结果为: 房子高度为 3 米 房子高度为 3 米 重载方法: 房子高度为 3 米 无参数构造函数 */
- Java 实例 – 输出数组元素
/* 以下实例演示了如何通过重载 MainClass 类的 printArray 方法输出不同类型(整型, 双精度及字符型)的数组: MainClass.java 文件 */ public class MainClass { public static void printArray(Integer[] inputArray) { for (Integer element : inputArray){ System.out.printf("%s ", element); System.out.println(); } } public static void printArray(Double[] inputArray) { for (Double element : inputArray){ System.out.printf("%s ", element); System.out.println(); } } public static void printArray(Character[] inputArray) { for (Character element : inputArray){ System.out.printf("%s ", element); System.out.println(); } } public static void main(String args[]) { Integer[] integerArray = { 1, 2, 3, 4, 5, 6 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("输出整型数组:"); printArray(integerArray); System.out.println("\n输出双精度型数组:"); printArray(doubleArray); System.out.println("\n输出字符型数组:"); printArray(characterArray); } } /* 以上代码运行输出结果为: 输出整型数组: 1 2 3 4 5 6 输出双精度型数组: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 输出字符型数组: H E L L O */
- Java 实例 – 汉诺塔算法
汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。 后来,这个传说就演变为汉诺塔游戏,玩法如下: 1.有三根杆子A,B,C。A杆上有若干碟子 2.每次移动一块碟子,小的只能叠在大的上面 3.把所有碟子从A杆全部移到C杆上
/* 以下实例演示了汉诺塔算法的实现: MainClass.java 文件 */ public class MainClass { public static void main(String[] args) { int nDisks = 3; doTowers(nDisks, 'A', 'B', 'C'); } public static void doTowers(int topN, char from, char inter, char to) { if (topN == 1){ System.out.println("Disk 1 from " + from + " to " + to); }else { doTowers(topN - 1, from, to, inter); System.out.println("Disk " + topN + " from " + from + " to " + to); doTowers(topN - 1, inter, from, to); } } } /* 以上代码运行输出结果为: Disk 1 from A to C Disk 2 from A to B Disk 1 from C to B Disk 3 from A to C Disk 1 from B to A Disk 2 from B to C Disk 1 from A to C */
- Java 实例 – 斐波那契数列
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368…… 特别指出:第0项是0,第1项是第一个1。 这个数列从第三项开始,每一项都等于前两项之和。
/* 以下实例演示了 Java 斐波那契数列的实现: * MainClass.java 文件 */ public class MainClass { public static long fibonacci(long number) { if ((number == 0) || (number == 1)) return number; else return fibonacci(number - 1) + fibonacci(number - 2); } public static void main(String[] args) { for (int counter = 0; counter <= 10; counter++){ System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter)); } } } /* 以上代码运行输出结果为: Fibonacci of 0 is: 0 Fibonacci of 1 is: 1 Fibonacci of 2 is: 1 Fibonacci of 3 is: 2 Fibonacci of 4 is: 3 Fibonacci of 5 is: 5 Fibonacci of 6 is: 8 Fibonacci of 7 is: 13 Fibonacci of 8 is: 21 Fibonacci of 9 is: 34 Fibonacci of 10 is: 55 */
- Java 实例 – 阶乘
一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1。自然数n的阶乘写作n!。 亦即n!=1×2×3×...×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。
/* 以下实例演示了 Java 阶乘代码的实现: * MainClass.java 文件 */ public class MainClass { public static void main(String args[]) { for (int counter = 0; counter <= 10; counter++){ System.out.printf("%d! = %d\n", counter, factorial(counter)); } } public static long factorial(long number) { if (number <= 1) return 1; else return number * factorial(number - 1); } } /* 以上代码运行输出结果为: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 */
- Java 实例 – 方法覆盖
方法重载与方法覆盖区别如下: 方法重载(Overloading):如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。 方法覆盖(Overriding):如果在子类中定义一个方法,其名称、返回类型及参数签名正好与父类中某个方法的名称、返回类型及参数签名相匹配,那么可以说,子类的方法覆盖了父类的方法。
/* 以下实例演示了 Java 方法覆盖(Overriding)代码的实现: * Findareas.java 文件 */ public class Findareas{ public static void main (String []agrs){ Figure f= new Figure(10 , 10); Rectangle r= new Rectangle(9 , 5); Figure figref; figref=f; System.out.println("Area is :"+figref.area()); figref=r; System.out.println("Area is :"+figref.area()); } } class Figure{ double dim1; double dim2; Figure(double a , double b) { dim1=a; dim2=b; } Double area() { System.out.println("Inside area for figure."); return(dim1*dim2); } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a ,b); } Double area() { System.out.println("Inside area for rectangle."); return(dim1*dim2); } } /* 以上代码运行输出结果为: Inside area for figure. Area is :100.0 Inside area for rectangle. Area is :45.0 */
- Java 实例 – instanceOf 关键字用法
instanceof 是 Java 的一个二元操作符,类似于 ==,>,< 等操作符。 instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。
/* 以下实例创建了 displayObjectClass() 方法来演示 Java instanceof 关键字用法: Main.java 文件代码: */ /* author by runoob.com Main.java */ import java.util.ArrayList; import java.util.Vector; public class Main { public static void main(String[] args) { Object testObject = new ArrayList(); displayObjectClass(testObject); } public static void displayObjectClass(Object o) { if (o instanceof Vector) System.out.println("对象是 java.util.Vector 类的实例"); else if (o instanceof ArrayList) System.out.println("对象是 java.util.ArrayList 类的实例"); else System.out.println("对象是 " + o.getClass() + " 类的实例"); } } /* 以上代码运行输出结果为: 对象是 java.util.ArrayList 类的实例 */
- Java 实例 – break 关键字用法
ava break 语句可以直接强行退出当前的循环,忽略循环体中任何其他语句和循环条件测试。 以下实例使用了 break 关键字来跳出当前循环:
/* Findareas.java 文件 */ public class Main { public static void main(String[] args) { int[] intary = { 99,12,22,34,45,67,5678,8990 }; int no = 5678; int i = 0; boolean found = false; for ( ; i < intary.length; i++) { if (intary[i] == no) { found = true; break; } } if (found) { System.out.println(no + " 元素的索引位置在: " + i); } else { System.out.println(no + " 元素不在数组总"); } } } /* 以上代码运行输出结果为: 5678 元素的索引位置在: 6 */
- Java 实例 – continue 关键字用法
Java continue 语句语句用来结束当前循环,并进入下一次循环,即仅仅这一次循环结束了,不是所有循环结束了,后边的循环依旧进行。 以下实例使用了 continue 关键字来跳过当前循环并开始下一次循环:
/* Main.java 文件 */ public class Main { public static void main(String[] args) { StringBuffer searchstr = new StringBuffer("hello how are you. "); int length = searchstr.length(); int count = 0; for (int i = 0; i < length; i++) { if (searchstr.charAt(i) != 'h') continue; count++; searchstr.setCharAt(i, 'h'); } System.out.println("发现 " + count + " 个 h 字符"); System.out.println(searchstr); } } /* 以上代码运行输出结果为: 发现 2 个 h 字符 hello how are you. */
- Java 实例 – 标签(Label)
Java 中的标签是为循环设计的,是为了在多重循环中方便的使用break 和coutinue 。 以下实例当在循环中使用 break 或 continue 循环时跳到指定的标签处:
/* Main.java 文件 */ public class Main { public static void main(String[] args) { String strSearch = "This is the string in which you have to search for a substring."; String substring = "substring"; boolean found = false; int max = strSearch.length() - substring.length(); testlbl: for (int i = 0; i <= max; i++) { int length = substring.length(); int j = i; int k = 0; while (length-- != 0) { if(strSearch.charAt(j++) != substring.charAt(k++)){ continue testlbl; } } found = true; break testlbl; } if (found) { System.out.println("发现子字符串。"); } else { System.out.println("字符串中没有发现子字符串。"); } } } /* 以上代码运行输出结果为: 发现子字符串。 */
- Java 实例 – enum 和 switch 语句使用
Java 创建枚举类型要使用 enum 关键字,隐含了所创建的类型都是 java.lang.Enum 类的子类 对enum进行遍历和switch的操作示例代码:
/* Main.java 文件 */ enum Car { lamborghini,tata,audi,fiat,honda } public class Main { public static void main(String args[]){ Car c; c = Car.tata; switch(c) { case lamborghini: System.out.println("你选择了 lamborghini!"); break; case tata: System.out.println("你选择了 tata!"); break; case audi: System.out.println("你选择了 audi!"); break; case fiat: System.out.println("你选择了 fiat!"); break; case honda: System.out.println("你选择了 honda!"); break; default: System.out.println("我不知道你的车型。"); break; } } } /* 以上代码运行输出结果为: 你选择了 tata! */
- Java 实例 – Enum(枚举)构造函数及方法的使用
/* 以下实例演示了Enum(枚举)构造函数及方法的使用: * Main.java 文件 */ enum Car { lamborghini(900),tata(2),audi(50),fiat(15),honda(12); private int price; Car(int p) { price = p; } int getPrice() { return price; } } public class Main { public static void main(String args[]){ System.out.println("所有汽车的价格:"); for (Car c : Car.values()) System.out.println(c + " 需要 " + c.getPrice() + " 千美元。"); } } /* 以上代码运行输出结果为: 所有汽车的价格: lamborghini 需要 900 千美元。 tata 需要 2 千美元。 audi 需要 50 千美元。 fiat 需要 15 千美元。 honda 需要 12 千美元。 */
- Java 实例 – for 和 foreach循环使用
for 语句比较简单,用于循环数据。 for 循环执行的次数是在执行前就确定的。语法格式如下:
for(初始化; 布尔表达式; 更新) { //代码语句 }
foreach 语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。 foreach 语法格式如下:
for(元素类型t 元素变量x : 遍历对象obj){ 引用了x的java语句; }
以下实例演示了 for 和 foreach循环使用:
/* Main.java 文件 */ public class Main { public static void main(String[] args) { int[] intary = { 1,2,3,4}; forDisplay(intary); foreachDisplay(intary); } public static void forDisplay(int[] a){ System.out.println("使用 for 循环数组"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static void foreachDisplay(int[] data){ System.out.println("使用 foreach 循环数组"); for (int a : data) { System.out.print(a+ " "); } } } /* 以上代码运行输出结果为: 使用 for 循环数组 1 2 3 4 使用 foreach 循环数组 1 2 3 4 */
- Java 实例 – Varargs 可变参数使用
Java1.5提供了一个叫varargs的新功能,就是可变长度的参数。 "Varargs"是"variable number of arguments"的意思。有时候也被简单的称为"variable arguments" 定义实参个数可变的方法:只要在一个形参的"类型"与"参数名"之间加上三个连续的"."(即"...",英文里的句中省略号),就可以让它和不确定个实参相匹配。 以下实例创建了 sumvarargs() 方法来统计所有数字的值:
/* Main.java 文件 */ public class Main { static int sumvarargs(int... intArrays){ int sum, i; sum=0; for(i=0; i< intArrays.length; i++) { sum += intArrays[i]; } return(sum); } public static void main(String args[]){ int sum=0; sum = sumvarargs(new int[]{10,12,33}); System.out.println("数字相加之和为: " + sum); } } /* 以上代码运行输出结果为: 数字相加之和为: 55 */
- Java 实例 – 重载(overloading)方法中使用可变参数 Varargs
/* Main.java 文件 */ public class Main { static void vaTest(int ... no) { System.out.print("vaTest(int ...): " + "参数个数: " + no.length +" 内容: "); for(int n : no) System.out.print(n + " "); System.out.println(); } static void vaTest(boolean ... bl) { System.out.print("vaTest(boolean ...) " + "参数个数: " + bl.length + " 内容: "); for(boolean b : bl) System.out.print(b + " "); System.out.println(); } static void vaTest(String msg, int ... no) { System.out.print("vaTest(String, int ...): " + msg +"参数个数: "+ no.length +" 内容: "); for(int n : no) System.out.print(n + " "); System.out.println(); } public static void main(String args[]){ vaTest(1, 2, 3); vaTest("测试: ", 10, 20); vaTest(true, false, false); } } /* 以上代码运行输出结果为: vaTest(int ...): 参数个数: 3 内容: 1 2 3 vaTest(String, int ...): 测试: 参数个数: 2 内容: 10 20 vaTest(boolean ...) 参数个数: 3 内容: true false false */
打印图形
- Java 实例 – 打印菱形
/* 输出指定行数的菱形。 实例 */ public class Diamond { public static void main(String[] args) { print(8); // 输出 8 行的菱形 } public static void print(int size) { if (size % 2 == 0) { size++; // 计算菱形大小 } for (int i = 0; i < size / 2 + 1; i++) { for (int j = size / 2 + 1; j > i + 1; j--) { System.out.print(" "); // 输出左上角位置的空白 } for (int j = 0; j < 2 * i + 1; j++) { System.out.print("*"); // 输出菱形上半部边缘 } System.out.println(); // 换行 } for (int i = size / 2 + 1; i < size; i++) { for (int j = 0; j < i - size / 2; j++) { System.out.print(" "); // 输出菱形左下角空白 } for (int j = 0; j < 2 * size - 1 - 2 * i; j++) { System.out.print("*"); // 输出菱形下半部边缘 } System.out.println(); // 换行 } } } /* 输出结果: * *** ***** ******* ********* ******* ***** *** * */
- Java 实例 – 九九乘法表
/* 输出九九乘法表。 实例 */ public class MultiplicationTable { public static void main(String[] args) { for(int i=1;i<=9;i++) { for(int j=1;j<=i;j++) { System.out.print(j+"×"+i+"="+i*j+"\t");// \t 跳到下一个TAB位置 } System.out.println(); } } } /* 输出结果: 1×1=1 1×2=2 2×2=4 1×3=3 2×3=6 3×3=9 1×4=4 2×4=8 3×4=12 4×4=16 1×5=5 2×5=10 3×5=15 4×5=20 5×5=25 1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36 1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49 1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64 1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81 */
- Java 实例 – 打印三角形
首先,确定我们的输出结果是:
那么我们怎么才能做到这样呢? 1、首先分析图形的结构 我们可以看到,图形共5行,那么,我们是否可以建立一个for循环语句,使其控制在5行?答案是肯定的。
for(int i = 1 ;i <= 5 ;i++ ){ }
这样,我们就建立了一个循环5次的for循环代码块,为最外圈的循环。
2、然后,分析图形是怎样构成的,我们可以把图形拆分为以下几部分:/p>我们可以把图形拆分为这样三个三角形。
3、建立1号空白三角形 可以看,第一行是输出4个空格,第二行输出3个空格,第三行输出2个,第四行输出1个,第五行没有 从这个规律可以看出,是依次递减的规律,那么如何实现呢? 我们可以想象从1到5,中间有四个数字;从2到5中间有3个数字,从3到5…… 是不是可以利用这个原理呢?答案是当然的。那么如何实现?请看代码:for(int i = 1;i<=5 ;i++) { for(int j = 5; j >= i ; j--)//建立1号图形 System.out.print(" "); System.out.println(); }
第一个for语句就是刚才定义的五次循环语句
第二个for循环,我们来进行解析:首先 定义一个int类型的j变量,给j赋值为5 然后我们想,既然要缩短距离,那么每次循环j就-1,那么刚好符合我们的要求: 第一次大循环 i=1,j=5, 所以符合j>=i的条件然后输出一个空格,然后j-1,现在j的值为4符合j>=i,再输出 …… 一直到j=0,j>=i不符合,跳出内循环 现在到System.out.println(); 换行 现在回到外循环 i++ ,i变成2,符合i<=5,进入内循环 定义j=5 , j>=i,符合,输出一个空格,j-1 j现在为4 ,j>=i,符合,输出一个空额,j-1 …… 一直到j=1,j>=i,不成立,跳出内训还,然后换行 然后i+1 然后再进入内循环…… 如此循环下去 形成了一个四行的倒三角,1号图案形成。 4、建立2号图形,和1号图形原理完全相同,不过正好相反
for(int i = 1 ;i<=5 ;i++){ for(int j = 5; j >= i ; j--)//建立1号图形 System.out.print(" "); for(int j = 1; j <= i; j++)//建立2号图形 System.out.print("*"); System.out.println(); }
如建立1号图形相同,大家可以自己理解,如此2号建立
5、建立3号图形
for(int i = 1; i <= 5; i++){ for(int j = 5 ;i <= j; j--)//建立1号图形 System.out.print(" "); for(int j = 1; j <= i; j++)//建立2号图形 System.out.print("*"); for(int j = 1; j < i; j ++)//建立3号图形 System.out.print("*"); }
同样,如同1号二号相同,建立3号图形原理相同
但是大家注意一点,3号图形没有在第一行输出,所以要在第一次大循环中掐断它,让它在第二次大循环中输出 所以 这次的判断条件为 j < i 去掉了等于。
class Demo{ public static void main(String[] args){ for(int i=1;i<=5;i++){ for(int j=5; i<=j; j--) System.out.print(" "); for(int j=1; j<=i; j++) System.out.print("*"); for(int j=1; j<i; j++) System.out.print("*"); System.out.println(); } } }
- Java 实例 – 打印倒立的三角形
public class InvertedTriangle { public static void main(String[] args) { //打印倒立的三角形 for (int m = 1; m <= 4; m++) { //打印空格 for (int n = 0; n <= m; n++) { System.out.print(" "); } //打印* for (int x = 1; x <= 7 -2 * (m - 1); x++) { System.out.print("*"); } System.out.println(); } } } /* 输出结果: ******* ***** *** * */
- Java 实例 – 打印平行四边形
public class Parallelogram { public static void main(String[] args) { //外层循环 每次打出一个* for (int i = 1; i <=5; i++) { //填充空格 for (int j = 1; j <= 5 - i; j++) { System.out.print(" "); } //内层循环 每次打印一个* for (int k = 1; k <= 5; k++) { System.out.print("*"); } System.out.println(); } } } /* 输出结果: ***** ***** ***** ***** ***** */
- Java 实例 – 打印矩形
public class Rect { public static void main(String[] args) { //外层循环 每次输出一行* for (int i = 1; i <= 5; i++) { System.out.print("*"); //内层循环 每次输出一个* for (int j = 1; j <= 5; j++) { System.out.print("*"); } System.out.println(); } } } /* 输出结果: ****** ****** ****** ****** ****** */
Java 文件操作
- Java 实例 - 文件写入
以下实例演示了使用 write() 方法向文件写入内容:
/* author by runoob.com Main.java */ import java.io.*; public class Main { public static void main(String[] args) { try { BufferedWriter out = new BufferedWriter(new FileWriter("runoob.txt")); out.write("菜鸟教程"); out.close(); System.out.println("文件创建成功!"); } catch (IOException e) { } } } /* 以上代码运行输出结果为: 文件创建成功! 创建成功后当前目录下就会生成一个名为 runoob.txt 的文件并将 "菜鸟教程" 字符串写入该文件。 */
- Java 实例 - 读取文件内容
以下实例演示了使用 readLine() 方法来读取文件 test.log 内容,其中 test.log 文件内容为:
教程 www.runoob.com
import java.io.*; public class Main { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader("test.log")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } System.out.println(str); } catch (IOException e) { } } } /* 以上代码运行输出结果为: 教程 www.runoob.com null */
- Java 实例 - 删除文件
/* Main.java 文件 */ public class Main { public static void main(String[] args) { try{ File file = new File("c:\\test.txt"); if(file.delete()){ System.out.println(file.getName() + " 文件已被删除!"); }else{ System.out.println("文件删除失败!"); } }catch(Exception e){ e.printStackTrace(); } } } /* 以上代码运行输出结果为(需要在 C 盘上先创建 test.txt 文件): test.txt 文件已被删除! */
- Java 实例 - 将文件内容复制到另一个文件
/* Main.java 文件 */ import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile")); out1.write("string to be copied\n"); out1.close(); InputStream in = new FileInputStream(new File("srcfile")); OutputStream out = new FileOutputStream (new File("destnfile")); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); BufferedReader in1 = new BufferedReader(new FileReader("destnfile")); String str; while ((str = in1.readLine()) != null) { System.out.println(str); } in1.close(); } } /* 以上代码运行输出结果为: string to be copied */
- Java 实例 - 向文件中追加数据
/* Main.java 文件 */ import java.io.*; public class Main { public static void main(String[] args) throws Exception { try { BufferedWriter out = new BufferedWriter(new FileWriter("filename")); out.write("aString1\n"); out.close(); out = new BufferedWriter(new FileWriter("filename",true)); out.write("aString2"); out.close(); BufferedReader in = new BufferedReader(new FileReader("filename")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (IOException e) { System.out.println("exception occoured"+ e); } } } /* 以上代码运行输出结果为: aString1 aString2 */
- Java 实例 - 创建临时文件
/* Main.java 文件 */ import java.io.*; public class Main { public static void main(String[] args) throws Exception { File temp = File.createTempFile("pattern", ".suffix"); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("aString"); System.out.println("临时文件已创建:"); out.close(); } } /* 以上代码运行输出结果为: 临时文件已创建: */
- Java 实例 - 修改文件最后的修改日期
以下实例演示了使用 File 类的 fileToChange.lastModified() 和 fileToChange setLastModified() 方法来修改文件最后的修改日期:
/* Main.java 文件 */ import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) throws Exception { File fileToChange = new File("C:/myjavafile.txt"); fileToChange.createNewFile(); Date filetime = new Date(fileToChange.lastModified()); System.out.println(filetime.toString()); System.out.println(fileToChange.setLastModified(System.currentTimeMillis())); filetime = new Date(fileToChange.lastModified()); System.out.println(filetime.toString()); } } /* 以上代码运行输出结果为: Sat Mar 21 22:00:48 CST 2015 true Fri Apr 10 11:09:19 CST 2015 */
- Java 实例 - 获取文件大小
以下实例演示了使用 File 类的 file.exists() 和 file.length() 方法来获取文件大小,以字节计算(1KB=1024字节 ):
/* Main.java 文件 */ import java.io.File; public class Main { public static long getFileSize(String filename) { File file = new File(filename); if (!file.exists() || !file.isFile()) { System.out.println("文件不存在"); return -1; } return file.length(); } public static void main(String[] args) { long size = getFileSize("c:/java.txt"); System.out.println("java.txt文件大小为: " + size); } } /* 以上代码运行输出结果为(java.txt 文件位于 C 盘): java.txt文件大小为: 480 */
- Java 实例 - 文件重命名
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File oldName = new File("C:/program.txt"); File newName = new File("C:/java.txt"); if(oldName.renameTo(newName)) { System.out.println("已重命名"); } else { System.out.println("Error"); } } } /* 以上代码运行输出结果为(执行该程序前你可以先创建 program.txt 文件): 已重命名 */
- Java 实例 - 设置文件只读
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:/java.txt"); System.out.println(file.setReadOnly()); System.out.println(file.canWrite()); } } /* 以上代码运行输出结果为: true false */
- Java 实例 - 检测文件是否存在
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:/java.txt"); System.out.println(file.exists()); } } /* 以上代码运行输出结果为(如果你的 C 盘中存在文件 java.txt): true */
- Java 实例 - 在指定目录中创建文件
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) throws Exception { File file = null; File dir = new File("C:/"); file = File.createTempFile ("JavaTemp", ".javatemp", dir); System.out.println(file.getPath()); } } /* 以上代码运行输出结果为: C:\JavaTemp37056.javatemp */
- Java 实例 - 获取文件修改时间
/* Main.java 文件 */ import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) { File file = new File("Main.java"); Long lastModified = file.lastModified(); Date date = new Date(lastModified); System.out.println(date); } } /* 以上代码运行输出结果为: Thu Apr 09 09:40:19 CST 2015 */
- Java 实例 - 创建文件
/* Main.java 文件 */ import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { try{ File file = new File("C:/myfile.txt"); if(file.createNewFile()) System.out.println("文件创建成功!"); else System.out.println("出错了,该文件已经存在。"); } catch(IOException ioe) { ioe.printStackTrace(); } } } /* 以上代码运行输出结果为: 文件创建成功! */
- Java 实例 - 文件路径比较
/* 使用 File 类的 filename.compareTo (another filename) 方法来比较两个文件路径是否在同一个目录下: * Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File file1 = new File("C:/File/demo1.txt"); File file2 = new File("C:/java/demo1.txt"); if(file1.compareTo(file2) == 0) { System.out.println("文件路径一致!"); } else { System.out.println("文件路径不一致!"); } } } /* 以上代码运行输出结果为: 文件路径不一致! */
Java 目录操作
- Java 实例 - 递归创建目录
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i"; File file = new File(directories); boolean result = file.mkdirs(); System.out.println("Status = " + result); } } /* 以上代码运行输出结果为: Status = true */
- Java 实例 - 删除目录
/* 使用 File 类的 ofdir.isDirectory(), dir.list() 和 deleteDir() 方法在一个个删除文件后删除目录 : * Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] argv) throws Exception { // 删除当前目录下的 test 目录 deleteDir(new File("./test")); } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir (new File(dir, children[i])); if (!success) { return false; } } } if(dir.delete()) { System.out.println("目录已被删除!"); return true; } else { System.out.println("目录删除失败!"); return false; } } } /* 以上代码运行输出结果为: 目录已被删除! */
- Java 实例 - 判断目录是否为空
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File file = new File("/data"); if (file.isDirectory()) { String[] files = file.list(); if (files.length > 0) { System.out.println("目录 " + file.getPath() + " 不为空!"); } } } } /* 以上代码运行输出结果为: 目录 D://Java/file.txt 不为空! */
- Java 实例 - 判断文件是否隐藏
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:/Demo.txt"); System.out.println(file.isHidden()); } } /* 以上代码运行输出结果为(Demo.txt为隐藏文件): True */
- Java 实例 - 获取目录大小
/* Main.java 文件 */ import java.io.File; import org.apache.commons.io.FileUtils; public class Main { public static void main(String[] args) { long size = FileUtils.sizeOfDirectory(new File("C:/test")); System.out.println("Size: " + size + " bytes"); } } /* 以上代码运行输出结果为: Size: 2048 bytes */
- Java 实例 - 在指定目录中查找文件
/* 以下实例演示了使用 File 类的 dir.list() 方法在指定目录中查找所有文件列表: Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] argv) throws Exception { File dir = new File("../java"); String[] children = dir.list(); if (children == null) { System.out.println("该目录不存在"); } else { for (int i = 0; i < children.length; i++) { String filename = children[i]; System.out.println(filename); } } } } /* 以上代码运行输出结果为: Car.class FileUtil.class FileUtil.java HelloWorld.class HelloWorld.java HelloWorldDebug.class HelloWorldDebug.java …… */
- Java 实例 - 获取文件的上级目录
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:/File/demo.txt"); String strParentDirectory = file.getParent(); System.out.println("文件的上级目录为 : " + strParentDirectory); } } /* 以上代码运行输出结果为: 文件的上级目录为 : File */
- Java 实例 - 获取目录最后修改时间
/* Main.java 文件 */ import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) { File file = new File("C://FileIO//demo.txt"); System.out.println("最后修改时间:" + new Date(file.lastModified())); } } /* 以上代码运行输出结果为: 最后修改时间:Fri Apr 10 11:09:19 CST 2015 */
- Java 实例 - 打印目录结构
/* Main.java 文件 */ import java.io.File; import java.io.IOException; public class FileUtil { public static void main(String[] a)throws IOException{ showDir(1, new File("d:\\Java")); } static void showDir(int indent, File file) throws IOException { for (int i = 0; i < indent; i++) System.out.print('-'); System.out.println(file.getName()); if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) showDir(indent + 4, files[i]); } } } /* 以上代码运行输出结果为: -Java -----codes ---------string.txt ---------array.txt -----w3cschoolcc */
- Java 实例 - 遍历指定目录下的所有目录
/* Main.java 文件 */ import java.io.*; class Main { public static void main(String[] args) { File dir = new File("F:"); File[] files = dir.listFiles(); FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; files = dir.listFiles(fileFilter); System.out.println(files.length); if (files.length == 0) { System.out.println("目录不存在或它不是一个目录"); } else { for (int i=0; i< files.length; i++) { File filename = files[i]; System.out.println(filename.toString()); } } } } /* 以上代码运行输出结果为: 14 F:\C Drive Data Old HDD F:\Desktop1 F:\harsh F:\hharsh final F:\hhhh F:\mov F:\msdownld.tmp F:\New Folder F:\ravi F:\ravi3 F:\RECYCLER F:\System Volume Information F:\temp F:\work */
- Java 实例 - 遍历指定目录下的所有文件
/* Main.java 文件 */ class Main { public static void main(String[] args) { File dir = new File("C:"); String[] children = dir.list(); if (children == null) { System.out.println( "目录不存在或它不是一个目录"); } else { for (int i=0; i< children.length; i++) { String filename = children[i]; System.out.println(filename); } } } } /* 以上代码运行输出结果为: build build.xml destnfile detnfile filename manifest.mf nbproject outfilename src srcfile test */
- Java 实例 - 在指定目录中查找文件
/* Main.java 文件 */ import java.io.*; class Main { public static void main(String[] args) { File dir = new File("C:"); FilenameFilter filter = new FilenameFilter() { public boolean accept (File dir, String name) { return name.startsWith("b"); } }; String[] children = dir.list(filter); if (children == null) { System.out.println("目录不存在或它不是一个目录"); } else { for (int i=0; i < children.length; i++) { String filename = children[i]; System.out.println(filename); } } } } /* 以上代码运行输出结果为: build build.xml */
- Java 实例 - 遍历系统根目录
/* Main.java 文件 */ import java.io.*; class Main{ public static void main(String[] args){ File[] roots = File.listRoots(); System.out.println("系统所有根目录:"); for (int i=0; i < roots.length; i++) { System.out.println(roots[i].toString()); } } } /* 以上代码运行输出结果为: 系统所有根目录: C:\ D:\ E:\ F:\ G:\ H:\ */
- Java 实例 - 查看当前工作目录
/* Main.java 文件 */ class Main { public static void main(String[] args) { String curDir = System.getProperty("user.dir"); System.out.println("你当前的工作目录为 :" + curDir); } } /* 以上代码运行输出结果为: 你当前的工作目录为 :/www/java */
- Java 实例 - 遍历目录
/* Main.java 文件 */ import java.io.File; public class Main { public static void main(String[] argv) throws Exception { System.out.println("遍历目录"); File dir = new File("/www/java"); //要遍历的目录 visitAllDirsAndFiles(dir); } public static void visitAllDirsAndFiles(File dir) { System.out.println(dir); if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { visitAllDirsAndFiles(new File(dir, children[i])); } } } } /* 以上代码运行输出结果为: 遍历目录 /www/java /www/java/Car.class /www/java/FileUtil.class /www/java/FileUtil.java /www/java/HelloWorld.class /www/java/HelloWorld.java /www/java/HelloWorldDebug.class /www/java/HelloWorldDebug.java /www/java/Main$1.class /www/java/Main.class /www/java/Main.java /www/java/MainClass.class /www/java/MainClass.java /www/java/MyClass.class /www/java/outfilename /www/java/test.log */
Java 异常处理
- Java 实例 - 异常处理方法
/* ExceptionDemo.java 文件 */ class ExceptionDemo { public static void main(String[] args) { try { throw new Exception("My Exception"); } catch (Exception e) { System.err.println("Caught Exception"); System.err.println("getMessage():" + e.getMessage()); System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.err.println("toString():" + e); System.err.println("printStackTrace():"); e.printStackTrace(); } } } /* 以上代码运行输出结果为: Caught Exception getMessage():My Exception getLocalizedMessage():My Exception toString():java.lang.Exception: My Exception printStackTrace(): java.lang.Exception: My Exception at ExceptionDemo.main(ExceptionDemo.java:5) */
- Java 实例 - 多个异常处理(多个catch)
对异常的处理: 1,声明异常时,建议声明更为具体的异常,这样可以处理的更具体 2,对方声明几个异常,就对应几个catch块, 如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面 以下实例演示了如何处理多异常:
/* ExceptionDemo.java 文件 */ class Demo { int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明该功能可能出现问题 { int []arr = new int [a]; System.out.println(arr[4]);//制造的第一处异常 return a/b;//制造的第二处异常 } } class ExceptionDemo { public static void main(String[]args) //throws Exception { Demo d = new Demo(); try { int x = d.div(4,0);//程序运行截图中的三组示例 分别对应此处的三行代码 //int x = d.div(5,0); //int x = d.div(4,1); System.out.println("x="+x); } catch (ArithmeticException e) { System.out.println(e.toString()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.toString()); } catch (Exception e)//父类 写在此处是为了捕捉其他没预料到的异常 只能写在子类异常的代码后面 //不过一般情况下是不写的 { System.out.println(e.toString()); } System.out.println("Over"); } } /* 以上代码运行输出结果为: java.lang.ArrayIndexOutOfBoundsException: 4 Over */
- Java 实例 - Finally的用法
Java 中的 Finally 关键一般与try一起使用,在程序进入try块之后,无论程序是因为异常而中止或其它方式返回终止的,finally块的内容一定会被执行 。 以下实例演示了如何使用 finally 通过 e.getMessage() 来捕获异常(非法参数异常):
/* ExceptionDemo2.java 文件 */ public class ExceptionDemo2 { public static void main(String[] argv) { new ExceptionDemo2().doTheWork(); } public void doTheWork() { Object o = null; for (int i=0; i<5; i++) { try { o = makeObj(i); } catch (IllegalArgumentException e) { System.err.println ("Error: ("+ e.getMessage()+")."); return; } finally { System.err.println("都已执行完毕"); if (o==null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1) throw new IllegalArgumentException ("不是指定的类型: " + type); return new Object(); } } /* 以上代码运行输出结果为: 都已执行完毕 java.lang.Object@7852e922 Error: (不是指定的类型:1). 都已执行完毕 */
- Java 实例 - 使用 catch 处理异常
/* Main.java 文件 */ public class Main { public static void main (String args[]) { int array[]={20,20,40}; int num1=15,num2=10; int result=10; try{ result = num1/num2; System.out.println("结果为 " +result); for(int i =5;i >=0; i--) { System.out.println ("数组的元素值为 " +array[i]); } } catch (Exception e) { System.out.println("触发异常 : "+e); } } } /* 以上代码运行输出结果为: 结果为 1 触发异常 : java.lang.ArrayIndexOutOfBoundsException: 5 */
- Java 实例 - 多线程异常处理
/* Main.java 文件 */ class MyThread extends Thread{ public void run(){ System.out.println("Throwing in " +"MyThread"); throw new RuntimeException(); } } class Main { public static void main(String[] args){ MyThread t = new MyThread(); t.start(); try{ Thread.sleep(1000); } catch (Exception x){ System.out.println("Caught it" + x); } System.out.println("Exiting main"); } } /* 以上代码运行输出结果为: Throwing in MyThread Exception in thread "Thread-0" java.lang.RuntimeException at testapp.MyThread.run(Main.java:19) Exiting main */
- Java 实例 - 获取异常的堆栈信息
/* 使用异常类的 printStack() 方法来获取堆栈信息: * Main.java 文件 */ public class Main{ public static void main (String args[]){ int array[]={20,20,40}; int num1=15,num2=10; int result=10; try{ result = num1/num2; System.out.println("The result is" +result); for(int i =5;i *gt;=0; i--) { System.out.println("The value of array is" +array[i]); } } catch (Exception e) { e.printStackTrace(); } } } /* 以上代码运行输出结果为: The result is1 java.lang.ArrayIndexOutOfBoundsException: 5 at testapp.Main.main(Main.java:28) */
- Java 实例 - 重载方法异常处理
/* Main.java 文件 */ public class Main { double method(int i) throws Exception{ return i/0; } boolean method(boolean b) { return !b; } static double method(int x, double y) throws Exception { return x + y ; } static double method(double x, double y) { return x + y - 3; } public static void main(String[] args) { Main mn = new Main(); try{ System.out.println(method(10, 20.0)); System.out.println(method(10.0, 20)); System.out.println(method(10.0, 20.0)); System.out.println(mn.method(10)); } catch (Exception ex){ System.out.println("exception occoure: "+ ex); } } } /* 以上代码运行输出结果为: 30.0 27.0 27.0 exception occoure: java.lang.ArithmeticException: / by zero */
- Java 实例 - 链试异常
/* Main.java 文件 */ public class Main { public static void main (String args[])throws Exception { int n=20,result=0; try{ result=n/0; System.out.println("结果为"+result); } catch(ArithmeticException ex){ System.out.println("发算术异常: "+ex); try { throw new NumberFormatException(); } catch(NumberFormatException ex1) { System.out.println("手动抛出链试异常 : "+ex1); } } } } /* 以上代码运行输出结果为: 发算术异常: java.lang.ArithmeticException: / by zero 手动抛出链试异常 : java.lang.NumberFormatException */
- Java 实例 - 自定义异常
/* TestInput.java 文件 */ class WrongInputException extends Exception { // 自定义的类 WrongInputException(String s) { super(s); } } class Input { void method() throws WrongInputException { throw new WrongInputException("Wrong input"); // 抛出自定义的类 } } class TestInput { public static void main(String[] args){ try { new Input().method(); } catch(WrongInputException wie) { System.out.println(wie.getMessage()); } } } /* 以上代码运行输出结果为: Wrong input */
Java 数据结构
- Java 实例 – 数字求和运算
/* TestInput.java 文件 */ public class Main { public static void main(String[] args) { int limit=100; int sum=0; int i=1; do { sum=sum+i; i++; } while(i<=limit); System.out.println("sum="+sum); } } /* 以上代码运行输出结果为: sum=5050 */
- Java 实例 – 利用堆栈将中缀表达式转换成后缀
/* InToPost.java 文件 */ import java.io.IOException; public class InToPost { private Stack theStack; private String input; private String output = ""; public InToPost(String in) { input = in; int stackSize = input.length(); theStack = new Stack(stackSize); } public String doTrans() { for (int j = 0; j < input.length(); j++) { char ch = input.charAt(j); switch (ch) { case '+': case '-': gotOper(ch, 1); break; case '*': case '/': gotOper(ch, 2); break; case '(': theStack.push(ch); break; case ')': gotParen(ch); break; default: output = output + ch; break; } } while (!theStack.isEmpty()) { output = output + theStack.pop(); } System.out.println(output); return output; } public void gotOper(char opThis, int prec1) { while (!theStack.isEmpty()) { char opTop = theStack.pop(); if (opTop == '(') { theStack.push(opTop); break; } else { int prec2; if (opTop == '+' || opTop == '-') prec2 = 1; else prec2 = 2; if (prec2 < prec1) { theStack.push(opTop); break; } else output = output + opTop; } } theStack.push(opThis); } public void gotParen(char ch){ while (!theStack.isEmpty()) { char chx = theStack.pop(); if (chx == '(') break; else output = output + chx; } } public static void main(String[] args) throws IOException { String input = "1+2*4/5-7+3/6"; String output; InToPost theTrans = new InToPost(input); output = theTrans.doTrans(); System.out.println("Postfix is " + output + '\n'); } class Stack { private int maxSize; private char[] stackArray; private int top; public Stack(int max) { maxSize = max; stackArray = new char[maxSize]; top = -1; } public void push(char j) { stackArray[++top] = j; } public char pop() { return stackArray[top--]; } public char peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } } } /* 以上代码运行输出结果为: 124*5/+7-36/+ Postfix is 124*5/+7-36/+ */
- Java 实例 – 在链表(LinkedList)的开头和结尾添加元素
/* Main.java 文件 */ import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList lList = new LinkedList(); lList.add("1"); lList.add("2"); lList.add("3"); lList.add("4"); lList.add("5"); System.out.println(lList); lList.addFirst("0"); System.out.println(lList); lList.addLast("6"); System.out.println(lList); } } /* 以上代码运行输出结果为: 1, 2, 3, 4, 5 0, 1, 2, 3, 4, 5 0, 1, 2, 3, 4, 5, 6 */
- Java 实例 – 获取链表(LinkedList)的第一个和最后一个元素:
/* 以下实例演示了如何使用 LinkedList 类的 linkedlistname.getFirst() 和 linkedlistname.getLast() 来获取链表的第一个和最后一个元素: Main.java 文件 */ import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList lList = new LinkedList(); lList.add("100"); lList.add("200"); lList.add("300"); lList.add("400"); lList.add("500"); System.out.println("链表的第一个元素是:" + lList.getFirst()); System.out.println("链表的第二个元素是:" + lList.getLast()); } } /* 以上代码运行输出结果为: 链表的第一个元素是:100 链表的第二个元素是:500 */
- Java 实例 – 删除链表中的元素
/* Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { LinkedList<String> lList = new LinkedList<String>(); lList.add("1"); lList.add("8"); lList.add("6"); lList.add("4"); lList.add("5"); System.out.println(lList); lList.subList(2, 4).clear(); System.out.println(lList); } } /* 以上代码运行输出结果为: [1, 8, 6, 4, 5] [1, 8, 5] */
- Java 实例 – 获取链表的元素
/* Main.java 文件 */ import java.util.*; public class Main { private LinkedList list = new LinkedList(); public void push(Object v) { list.addFirst(v); } public Object top() { return list.getFirst(); } public Object pop() { return list.removeFirst(); } public static void main(String[] args) { Main stack = new Main(); for (int i = 30; i < 40; i++) stack.push(new Integer(i)); System.out.println(stack.top()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } } /* 以上代码运行输出结果为: 39 39 38 37 */
- Java 实例 – 获取向量元素的索引值
/* 以下实例演示了使用 Collections 类的 sort() 方法对向量进行排序并使用 binarySearch() 方法来获取向量元素的索引值: Main.java 文件 */ import java.util.Collections; import java.util.Vector; public class Main { public static void main(String[] args) { Vector v = new Vector(); v.add("X"); v.add("M"); v.add("D"); v.add("A"); v.add("O"); Collections.sort(v); System.out.println(v); int index = Collections.binarySearch(v, "D"); System.out.println("元素索引值为 : " + index); } } /* 以上代码运行输出结果为: [A, D, M, O, X] 元素索引值为 : 1 */
- Java 实例 – 栈的实现
/* 以下实例演示了用户如何通过创建用于插入元素的自定义函数 push() 方法和用于弹出元素的 pop() 方法来实现栈: * MyStack.java 文件 */ public class MyStack { private int maxSize; private long[] stackArray; private int top; public MyStack(int s) { maxSize = s; stackArray = new long[maxSize]; top = -1; } public void push(long j) { stackArray[++top] = j; } public long pop() { return stackArray[top--]; } public long peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == maxSize - 1); } public static void main(String[] args) { MyStack theStack = new MyStack(10); theStack.push(10); theStack.push(20); theStack.push(30); theStack.push(40); theStack.push(50); while (!theStack.isEmpty()) { long value = theStack.pop(); System.out.print(value); System.out.print(" "); } System.out.println(""); } } /* 以上代码运行输出结果为: 50 40 30 20 10 */
- Java 实例 – 链表元素查找
/* 以下实例演示了使用 linkedlistname.indexof(element) 和 linkedlistname.Lastindexof(elementname) 方法在链表中获取元素第一次和最后一次出现的位置: Main.java 文件 */ import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList lList = new LinkedList(); lList.add("1"); lList.add("2"); lList.add("3"); lList.add("4"); lList.add("5"); lList.add("2"); System.out.println("元素 2 第一次出现的位置:" + lList.indexOf("2")); System.out.println("元素 2 最后一次出现的位置:"+ lList.lastIndexOf("2")); } } /* 以上代码运行输出结果为: 元素 2 第一次出现的位置:1 元素 2 最后一次出现的位置:5 */
- Java 实例 – 压栈出栈的方法实现字符串反转
/* 以下实例演示了使用用户自定义的方法 StringReverserThroughStack() 来实现字符串反转: StringReverserThroughStack.java 文件 */ import java.io.IOException; public class StringReverserThroughStack { private String input; private String output; public StringReverserThroughStack(String in) { input = in; } public String doRev() { int stackSize = input.length(); Stack theStack = new Stack(stackSize); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); theStack.push(ch); } output = ""; while (!theStack.isEmpty()) { char ch = theStack.pop(); output = output + ch; } return output; } public static void main(String[] args) throws IOException { String input = "www.w3cschool.cc"; String output; StringReverserThroughStack theReverser = new StringReverserThroughStack(input); output = theReverser.doRev(); System.out.println("反转前: " + input); System.out.println("反转后: " + output); } class Stack { private int maxSize; private char[] stackArray; private int top; public Stack(int max) { maxSize = max; stackArray = new char[maxSize]; top = -1; } public void push(char j) { stackArray[++top] = j; } public char pop() { return stackArray[top--]; } public char peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } } } /* 以上代码运行输出结果为: 反转前: www.w3cschool.cc 反转后: cc.loohcsc3w.www */
- Java 实例 – 队列(Queue)用法
队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。 LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。 以下实例演示了队列(Queue)的用法:
/* Main.java 文件 */ import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) { //add()和remove()方法在失败的时候会抛出异常(不推荐) Queue<String> queue = new LinkedList<String>(); //添加元素 queue.offer("a"); queue.offer("b"); queue.offer("c"); queue.offer("d"); queue.offer("e"); for(String q : queue){ System.out.println(q); } System.out.println("==="); System.out.println("poll="+queue.poll()); //返回第一个元素,并在队列中删除 for(String q : queue){ System.out.println(q); } System.out.println("==="); System.out.println("element="+queue.element()); //返回第一个元素 for(String q : queue){ System.out.println(q); } System.out.println("==="); System.out.println("peek="+queue.peek()); //返回第一个元素 for(String q : queue){ System.out.println(q); } } } /* 以上代码运行输出结果为: a b c d e === poll=a b c d e === element=b b c d e === peek=b b c d e */
- Java 实例 – 获取向量的最大元素
/* 以下实例演示了使用 Vector 类的 v.add() 方法及 Collection 类的 Collections.max() 来获取向量的最大元素: Main.java 文件 */ import java.util.Collections; import java.util.Vector; public class Main { public static void main(String[] args) { Vector v = new Vector(); v.add(new Double("3.4324")); v.add(new Double("3.3532")); v.add(new Double("3.342")); v.add(new Double("3.349")); v.add(new Double("2.3")); Object obj = Collections.max(v); System.out.println("最大元素是:"+obj); } } /* 以上代码运行输出结果为: 最大元素是:3.4324 */
- Java 实例 – 链表修改
/* 以下实例演示了使用 listname.add() 和 listname.set() 方法来修改链接中的元素: Main.java 文件 */ import java.util.LinkedList; public class Main { public static void main(String[] a) { LinkedList officers = new LinkedList(); officers.add("B"); officers.add("B"); officers.add("T"); officers.add("H"); officers.add("P"); System.out.println(officers); officers.set(2, "M"); System.out.println(officers); } } /* 以上代码运行输出结果为: [B, B, T, H, P] [B, B, M, H, P] */
- Java 实例 – 旋转向量
/* 以下实例演示了使用 swap() 函数来旋转向量: Main.java 文件 */ import java.util.Collections; import java.util.Vector; public class Main { public static void main(String[] args) { Vector<String> v = new Vector(); v.add("1"); v.add("2"); v.add("3"); v.add("4"); v.add("5"); System.out.println(v); Collections.swap(v, 0, 4); System.out.println("旋转后"); System.out.println(v); } } /* 以上代码运行输出结果为: 1 2 3 4 5 旋转后 5 2 3 4 1 */
Java 集合
- Java 实例 – 数组转集合
/* 以下实例演示了使用 Java Util 类的 Arrays.asList(name) 方法将数组转换为集合: ArrayToCollection.java 文件 */ import java.util.*; import java.io.*; public class ArrayToCollection{ public static void main(String args[]) throws IOException{ int n = 5; // 5 个元素 String[] name = new String[n]; for(int i = 0; i < n; i++){ name[i] = String.valueOf(i); } List<String> list = Arrays.asList(name); System.out.println(); for(String li: list){ String str = li; System.out.print(str + " "); } } } /* 以上代码运行输出结果为: 0 1 2 3 4 */
- Java 实例 – 集合比较
/* 以下实例将字符串转换为集合并使用 Collection 类的 Collection.min() 和 Collection.max() 来比较集合中的元素: Main.java 文件 */ import java.util.Collections; import java.util.Set; import java.util.TreeSet; class Main { public static void main(String[] args) { String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" }; Set set = new TreeSet(); for (int i = 0; i < coins.length; i++) set.add(coins[i]); System.out.println(Collections.min(set)); System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER)); for(int i=0;i<=10;i++) System.out.print("-"); System.out.println(""); System.out.println(Collections.max(set)); System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER)); } } /* 以上代码运行输出结果为: Penny dime ----------- nickel Quarter */
- Java 实例 – HashMap遍历
/* 以下实例演示了如何使用 Collection 类的 iterator() 方法来遍历集合: Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { HashMap< String, String> hMap = new HashMap< String, String>(); hMap.put("1", "1st"); hMap.put("2", "2nd"); hMap.put("3", "3rd"); Collection cl = hMap.values(); Iterator itr = cl.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } } /* 以上代码运行输出结果为: 1st 2nd 3rd */
- Java 实例 – 集合长度
/* 以下实例演示了如何使用 Collections 类 的collection.add() 来添加数据并使用 collection.size()来计算集合的长度: Main.java 文件 */ import java.util.*; public class Main { public static void main(String [] args) { System.out.println( "集合实例!\n" ); int size; HashSet collection = new HashSet (); String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator; collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4); System.out.print("集合数据: "); iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); size = collection.size(); if (collection.isEmpty()){ System.out.println("集合是空的"); } else{ System.out.println( "集合长度: " + size); } System.out.println(); } } /* 以上代码运行输出结果为: 集合实例! 集合数据: White Yellow Blue Green 集合长度: 4 */
- Java 实例 – 集合打乱顺序
/* 以下实例演示了如何使用 Collections 类 Collections.shuffle() 方法来打乱集合元素的顺序: Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) list.add(new Integer(i)); System.out.println("打乱前:"); System.out.println(list); for (int i = 1; i < 6; i++) { System.out.println("第" + i + "次打乱:"); Collections.shuffle(list); System.out.println(list); } } } /* 以上代码运行输出结果为: 打乱前: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 第1次打乱: [2, 0, 5, 1, 4, 9, 7, 6, 3, 8] 第2次打乱: [2, 6, 4, 8, 5, 7, 9, 1, 0, 3] 第3次打乱: [6, 5, 1, 0, 3, 7, 2, 4, 9, 8] 第4次打乱: [1, 3, 8, 4, 7, 2, 0, 6, 5, 9] 第5次打乱: [3, 0, 7, 9, 5, 8, 4, 2, 1, 6] */
- Java 实例 – 集合遍历
以下实例演示了如何遍历从Collection接口延伸出的List、Set和以键值对形式作存储的Map类型的集合,以下我们分别使用了普通for,增强型的 for ,iterator 等方式来遍历集合:
List与Set类型集合的遍历
/* List与Set类型集合的遍历 Main.java 文件 */ import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class Main { public static void main(String[] args) { // List集合的遍历 listTest(); // Set集合的遍历 setTest(); } private static void setTest() { Set<String> set = new HashSet<String>(); set.add("JAVA"); set.add("C"); set.add("C++"); // 重复数据添加失败 set.add("JAVA"); set.add("JAVASCRIPT"); // 使用iterator遍历set集合 Iterator<String> it = set.iterator(); while (it.hasNext()) { String value = it.next(); System.out.println(value); } // 使用增强for循环遍历set集合 for(String s: set){ System.out.println(s); } } // 遍历list集合 private static void listTest() { List<String> list = new ArrayList<String>(); list.add("教"); list.add("程"); list.add("www.w3cschool.cc"); // 使用iterator遍历 Iterator<String> it = list.iterator(); while (it.hasNext()) { String value = it.next(); System.out.println(value); } // 使用传统for循环进行遍历 for (int i = 0, size = list.size(); i < size; i++) { String value = list.get(i); System.out.println(value); } // 使用增强for循环进行遍历 for (String value : list) { System.out.println(value); } } } /* 以上代码运行输出结果为: 教 程 www.w3cschool.cc 教 程 www.w3cschool.cc 教 程 www.w3cschool.cc JAVA JAVASCRIPT C++ C JAVA JAVASCRIPT C++ C */
关于Map类型集合的遍历
以下实例我们使用了 HashMap 的 keySet()与entrySet()方法来遍历集合:
/* author by w3cschool.cc Main.java */ import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Map.Entry; //增强For循环 public class Main { public static void main(String[] args) { // 创建一个HashMap对象,并加入了一些键值对。 Map<String, String> maps = new HashMap<String, String>(); maps.put("1", "PHP"); maps.put("2", "Java"); maps.put("3", "C"); maps.put("4", "C++"); maps.put("5", "HTML"); // 传统的遍历map集合的方法1; keySet() //traditionalMethod1(maps); // 传统的遍历map集合的方法2; entrySet() //traditionalMethod2(maps); // 使用增强For循环来遍历map集合方法1; keySet() //strongForMethod1(maps); // 使用增强For循环来遍历map集合方法2; entrySet() strongForMethod2(maps); } private static void strongForMethod2(Map<String, String> maps) { Set<Entry<String, String>> set = maps.entrySet(); for (Entry<String, String> entry : set) { String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + " : " + value); } } private static void strongForMethod1(Map<String, String> maps) { Set<String> set = maps.keySet(); for (String s : set) { String key = s; String value = maps.get(s); System.out.println(key + " : " + value); } } // 使用entrySet()方法,获取maps集合中的每一个键值对, private static void traditionalMethod2(Map<String, String> maps) { Set<Map.Entry<String, String>> sets = maps.entrySet(); // 取得迭代器遍历出对应的值。 Iterator<Entry<String, String>> it = sets.iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = (Entry<String, String>) it.next(); String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + " : " + value); } } // 使用keySet()方法,获取maps集合中的所有键,遍历键取得所对应的值。 private static void traditionalMethod1(Map<String, String> maps) { Set<String> sets = maps.keySet(); // 取得迭代器遍历出对应的值 Iterator<String> it = sets.iterator(); while (it.hasNext()) { String key = it.next(); String value = maps.get(key); System.out.println(key + " : " + value); } } } /* 以上代码运行输出结果为: 1 : PHP 2 : Java 3 : C 4 : C++ 5 : HTML */
- Java 实例 – 集合反转
/* 以下实例演示了如何使用 Collection 和 Listiterator 类的 listIterator() 和 collection.reverse() 方法来反转集合中的元素: Main.java 文件 */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; class Main { public static void main(String[] args) { String[] coins = { "A", "B", "C", "D", "E" }; List l = new ArrayList(); for (int i = 0; i < coins.length; i++) l.add(coins[i]); ListIterator liter = l.listIterator(); System.out.println("反转前"); while (liter.hasNext()) System.out.println(liter.next()); Collections.reverse(l); liter = l.listIterator(); System.out.println("反转后"); while (liter.hasNext()) System.out.println(liter.next()); } } /*以上代码运行输出结果为: 反转前 A B C D E 反转后 E D C B A */
- Java 实例 – 删除集合中指定元素
/* 以下实例演示了如何使用 Collection 类的 collection.remove() 方法来删除集合中的指定的元素: Main.java 文件 */ import java.util.*; public class Main { public static void main(String [] args) { System.out.println( "集合实例!\n" ); int size; HashSet collection = new HashSet (); String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator; collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4); System.out.print("集合数据: "); iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); collection.remove(str2); System.out.println("删除之后 [" + str2 + "]\n"); System.out.print("现在集合的数据是: "); iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); size = collection.size(); System.out.println("集合大小: " + size + "\n"); } } /* 以上代码运行输出结果为: 集合实例! 集合数据: White Yellow Blue Green 删除之后 [White] 现在集合的数据是: Yellow Blue Green 集合大小: 3 */
- Java 实例 – 只读集合
/* 以下实例演示了如何使用 Collection 类的 Collections.unmodifiableList() 方法来设置集合为只读: Main.java 文件 */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] argv) throws Exception { List stuff = Arrays.asList(new String[] { "a", "b" }); List list = new ArrayList(stuff); list = Collections.unmodifiableList(list); try { list.set(0, "new value"); } catch (UnsupportedOperationException e) { } Set set = new HashSet(stuff); set = Collections.unmodifiableSet(set); Map map = new HashMap(); map = Collections.unmodifiableMap(map); System.out.println("集合现在是只读"); } } /* 以上代码运行输出结果为: 集合现在是只读 */
- Java 实例 – 集合输出
/* 以下实例演示了如何使用 Java Util 类的 tMap.keySet(),tMap.values() 和 tMap.firstKey() 方法将集合元素输出: Main.java 文件 */ import java.util.*; public class Main{ public static void main(String[] args) { System.out.println("TreeMap 实例!\n"); TreeMap tMap = new TreeMap(); tMap.put(1, "Sunday"); tMap.put(2, "Monday"); tMap.put(3, "Tuesday"); tMap.put(4, "Wednesday"); tMap.put(5, "Thursday"); tMap.put(6, "Friday"); tMap.put(7, "Saturday"); System.out.println("TreeMap 键:" + tMap.keySet()); System.out.println("TreeMap 值:" + tMap.values()); System.out.println("键为 5 的值为: " + tMap.get(5)+ "\n"); System.out.println("第一个键: " + tMap.firstKey() + " Value: " + tMap.get(tMap.firstKey()) + "\n"); System.out.println("最后一个键: " + tMap.lastKey() + " Value: "+ tMap.get(tMap.lastKey()) + "\n"); System.out.println("移除第一个数据: " + tMap.remove(tMap.firstKey())); System.out.println("现在 TreeMap 键为: " + tMap.keySet()); System.out.println("现在 TreeMap 包含: " + tMap.values() + "\n"); System.out.println("移除最后一个数据: " + tMap.remove(tMap.lastKey())); System.out.println("现在 TreeMap 键为: " + tMap.keySet()); System.out.println("现在 TreeMap 包含: " + tMap.values()); } } /* 以上代码运行输出结果为: TreeMap 实例! TreeMap 键:[1, 2, 3, 4, 5, 6, 7] TreeMap 值:[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] 键为 5 的值为: Thursday 第一个键: 1 Value: Sunday 最后一个键: 7 Value: Saturday 移除第一个数据: Sunday 现在 TreeMap 键为: [2, 3, 4, 5, 6, 7] 现在 TreeMap 包含: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] 移除最后一个数据: Saturday 现在 TreeMap 键为: [2, 3, 4, 5, 6] 现在 TreeMap 包含: [Monday, Tuesday, Wednesday, Thursday, Friday] */
- Java 实例 – 集合转数组
/* 以下实例演示了如何使用 Java Util 类的 list.add() 和 list.toArray() 方法将集合转为数组: Main.java 文件 */ import java.util.*; public class Main{ public static void main(String[] args){ List<String> list = new ArrayList<String>(); list.add("教"); list.add("程"); list.add("www.runoob.com"); String[] s1 = list.toArray(new String[0]); for(int i = 0; i < s1.length; ++i){ String contents = s1[i]; System.out.print(contents); } } } /* 以上代码运行输出结果为: 教程www.runoob.com */
- Java 实例 – List 循环移动元素
/* 以下实例演示了如何使用 Collections 类的 rotate() 来循环移动元素,方法第二个参数指定了移动的起始位置: Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six".split(" ")); System.out.println("List :"+list); Collections.rotate(list, 3); System.out.println("rotate: " + list); } } /* 以上代码运行输出结果为: List :[one, Two, three, Four, five, six] rotate: [Four, five, six, one, Two, three] */
- Java 实例 – 查找 List 中的最大最小值
/* 以下实例演示了如何使用 Collections 类的 max() 和 min() 方法来获取List中最大最小值: Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one three Four".split(" ")); System.out.println(list); System.out.println("最大值: " + Collections.max(list)); System.out.println("最小值: " + Collections.min(list)); } } /* 以上代码运行输出结果为: [one, Two, three, Four, five, six, one, three, Four] 最大值: three 最小值: Four */
- Java 实例 – 遍历 HashTable 的键值
/* 以下实例演示了如何使用 Hashtable 类的 keys() 方法来遍历输出键值: Main.java 文件 */ import java.util.Enumeration; import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable ht = new Hashtable(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); Enumeration e = ht.keys(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } } } /* 以上代码运行输出结果为: 3 2 1 */
- Java 实例 – 使用 Enumeration 遍历 HashTable
/* 以下实例演示了如何使用 Enumeration 类的 hasMoreElements 和 nextElement 方法来遍历输出 HashTable 中的内容: Main.java 文件 */ import java.util.Enumeration; import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable ht = new Hashtable(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); Enumeration e = ht.elements(); while(e.hasMoreElements()){ System.out.println(e.nextElement()); } } } /* 以上代码运行输出结果为: Three Two One */
- Java 实例 – 集合中添加不同类型元素
/* 以下实例演示了在集合类中添加不同类型的元素: Main.java 文件 */ import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; public class Main { public static void main(String[] args) { List lnkLst = new LinkedList(); lnkLst.add("element1"); lnkLst.add("element2"); lnkLst.add("element3"); lnkLst.add("element4"); displayAll(lnkLst); List aryLst = new ArrayList(); aryLst.add("x"); aryLst.add("y"); aryLst.add("z"); aryLst.add("w"); displayAll(aryLst); Set hashSet = new HashSet(); hashSet.add("set1"); hashSet.add("set2"); hashSet.add("set3"); hashSet.add("set4"); displayAll(hashSet); SortedSet treeSet = new TreeSet(); treeSet.add("1"); treeSet.add("2"); treeSet.add("3"); treeSet.add("4"); displayAll(treeSet); LinkedHashSet lnkHashset = new LinkedHashSet(); lnkHashset.add("one"); lnkHashset.add("two"); lnkHashset.add("three"); lnkHashset.add("four"); displayAll(lnkHashset); Map map1 = new HashMap(); map1.put("key1", "J"); map1.put("key2", "K"); map1.put("key3", "L"); map1.put("key4", "M"); displayAll(map1.keySet()); displayAll(map1.values()); SortedMap map2 = new TreeMap(); map2.put("key1", "JJ"); map2.put("key2", "KK"); map2.put("key3", "LL"); map2.put("key4", "MM"); displayAll(map2.keySet()); displayAll(map2.values()); LinkedHashMap map3 = new LinkedHashMap(); map3.put("key1", "JJJ"); map3.put("key2", "KKK"); map3.put("key3", "LLL"); map3.put("key4", "MMM"); displayAll(map3.keySet()); displayAll(map3.values()); } static void displayAll(Collection col) { Iterator itr = col.iterator(); while (itr.hasNext()) { String str = (String) itr.next(); System.out.print(str + " "); } System.out.println(); } } /* 以上代码运行输出结果为: element1 element2 element3 element4 x y z w set3 set2 set4 set1 1 2 3 4 one two three four key1 key2 key3 key4 J K L M key1 key2 key3 key4 JJ KK LL MM key1 key2 key3 key4 JJJ KKK LLL MMM */
- Java 实例 – List 元素替换
/* 以下实例演示了如何使用 Collections 类的 replaceAll() 来替换List中所有的指定元素: Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one three Four".split(" ")); System.out.println("List :"+list); Collections.replaceAll(list, "one", "hundrea"); System.out.println("replaceAll: " + list); } } /* 以上代码运行输出结果为: List :[one, Two, three, Four, five, six, one, three, Four] replaceAll: [hundrea, Two, three, Four, five, six, hundrea, three, Four] */
- Java 实例 – List 截取
/* 以下实例演示了如何使用 Collections 类的 indexOfSubList() 和 lastIndexOfSubList() 方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置: Main.java 文件 */ import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one three Four".split(" ")); System.out.println("List :"+list); List sublist = Arrays.asList("three Four".split(" ")); System.out.println("子列表 :"+sublist); System.out.println("indexOfSubList: " + Collections.indexOfSubList(list, sublist)); System.out.println("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist)); } } /* 以上代码运行输出结果为: List :[one, Two, three, Four, five, six, one, three, Four] 子列表 :[three, Four] indexOfSubList: 2 lastIndexOfSubList: 7 */
Java 网络实例
- Java 实例 – 获取指定主机的IP地址
/* 以下实例演示了如何使用 InetAddress 类的 InetAddress.getByName() 方法来获取指定主机(网址)的IP地址: Main.java 文件 */ import java.net.InetAddress; import java.net.UnknownHostException; public class GetIP { public static void main(String[] args) { InetAddress address = null; try { address = InetAddress.getByName("www.runoob.com"); } catch (UnknownHostException e) { System.exit(2); } System.out.println(address.getHostName() + "=" + address.getHostAddress()); System.exit(0); } } /* 以上代码运行输出结果为: www.runoob.com=222.73.134.120 */
- Java 实例 – 查看端口是否已使用
/* 以下实例演示了如何检测端口是否已经使用: Main.java 文件 */ import java.net.*; import java.io.*; public class Main { public static void main(String[] args) { Socket Skt; String host = "localhost"; if (args.length > 0) { host = args[0]; } for (int i = 0; i < 1024; i++) { try { System.out.println("查看 "+ i); Skt = new Socket(host, i); System.out.println("端口 " + i + " 已被使用"); } catch (UnknownHostException e) { System.out.println("Exception occured"+ e); break; } catch (IOException e) { } } } } /* 以上代码运行输出结果为: …… 查看 17 查看 18 查看 19 查看 20 查看 21 端口 21 已被使用 查看 22 查看 23 查看 24 …… */
- Java 实例 – 获取本机ip地址及主机名
/* 以下实例演示了如何使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名: Main.java 文件 */ import java.net.InetAddress; public class Main { public static void main(String[] args) throws Exception { InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local HostAddress: "+addr.getHostAddress()); String hostname = addr.getHostName(); System.out.println("Local host name: "+hostname); } } /* 以上代码运行输出结果为: Local HostAddress: 192.168.1.4 Local host name: harsh */
- Java 实例 – 获取远程文件大小
/* 以下实例演示了如何获取远程文件的大小: * Main.java 文件 */ import java.net.URL; import java.net.URLConnection; public class Main { public static void main(String[] argv) throws Exception { int size; URL url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png"); URLConnection conn = url.openConnection(); size = conn.getContentLength(); if (size < 0) System.out.println("无法获取文件大小。"); else System.out.println("文件大小为:" + size + " bytes"); conn.getInputStream().close(); } } /* 以上代码运行输出结果为: 文件大小为:4261 bytes */
- Java 实例 – Socket 实现多线程服务器程序
/* 以下实例演示了如何使用 Socket 类的 accept() 方法和 ServerSocket 类的 MultiThreadServer(socketname) 方法来实现多线程服务器程序: Main.java 文件 */ import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class MultiThreadServer implements Runnable { Socket csocket; MultiThreadServer(Socket csocket) { this.csocket = csocket; } public static void main(String args[]) throws Exception { ServerSocket ssock = new ServerSocket(1234); System.out.println("Listening"); while (true) { Socket sock = ssock.accept(); System.out.println("Connected"); new Thread(new MultiThreadServer(sock)).start(); } } public void run() { try { PrintStream pstream = new PrintStream (csocket.getOutputStream()); for (int i = 100; i >= 0; i--) { pstream.println(i + " bottles of beer on the wall"); } pstream.close(); csocket.close(); } catch (IOException e) { System.out.println(e); } } } /* 以上代码运行输出结果为: Listening Connected */
- Java 实例 – 查看主机指定文件的最后修改时间
/* 以下实例演示了如何查看主机指定文件的最后修改时间: Main.java 文件 */ import java.net.URL; import java.net.URLConnection; public class Main { public static void main(String[] argv) throws Exception { URL u = new URL("http://127.0.0.1/java.bmp"); URLConnection uc = u.openConnection(); uc.setUseCaches(false); long timestamp = uc.getLastModified(); System.out.println("java.bmp 文件最后修改时间 :"+timestamp); } } /* 以上代码运行输出结果为: java.bmp 文件最后修改时间 24 May 2014 12:14:50 */
- Java 实例 – 使用 Socket 连接到指定主机
/* 以下实例演示了如何使用 net.Socket 类的 getInetAddress() 方法来连接到指定主机: Main.java 文件 */ import java.net.InetAddress; import java.net.Socket; public class WebPing { public static void main(String[] args) { try { InetAddress addr; Socket sock = new Socket("www.runoob.com", 80); addr = sock.getInetAddress(); System.out.println("连接到 " + addr); sock.close(); } catch (java.io.IOException e) { System.out.println("无法连接 " + args[0]); System.out.println(e); } } } /* 以上代码运行输出结果为: 连接到 http:/www.runoob.com/222.73.134.120 */
- Java 实例 – 网页抓取
/* 以下实例演示了如何使用 net.URL 类的 URL() 构造函数来抓取网页: Main.java 文件 */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStreamReader; import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://www.runoob.com"); BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter (new FileWriter("data.html")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } reader.close(); writer.close(); } } /* 以上代码运行输出结果为(网页的源代码,存储在当前目录下的 data.html 文件中): <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8"/>…… */
- Java 实例 – 获取 URL响应头的日期信息
/* 以下实例演示了如何使用 HttpURLConnection 的 httpCon.getDate() 方法来获取 URL响应头的日期信息: Main.java 文件 */ import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; public class Main{ public static void main(String args[]) throws Exception { URL url = new URL("http://www.runoob.com"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); long date = httpCon.getDate(); if (date == 0) System.out.println("无法获取信息。"); else System.out.println("Date: " + new Date(date)); } } /* 以上代码运行输出结果为: Date: Mon May 04 11:57:06 CST 2015 */
- Java 实例 – 获取 URL 响应头信息
/* 以下实例演示了如何获取指定 URL 的响应头信息: Main.java 文件 */ import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) throws IOException{ URL url = new URL("http://www.runoob.com"); URLConnection conn = url.openConnection(); Map headers = conn.getHeaderFields(); Set<String> keys = headers.keySet(); for( String key : keys ){ String val = conn.getHeaderField(key); System.out.println(key+" "+val); } System.out.println( conn.getLastModified() ); } } /* 以上代码运行输出结果为: Transfer-Encoding chunked null HTTP/1.1 200 OK Server Tengine/1.3.0 Connection keep-alive Vary Cookie Date Mon, 04 May 2015 03:54:05 GMT X-Pingback http://www.runoob.com/xmlrpc.php X-Powered-By PHP/5.3.15 Content-Type text/html; charset=UTF-8 */
- Java 实例 – 解析 URL
/* 以下实例演示了如何使用 net.URL 类的 url.getProtocol() ,url.getFile() 等方法来解析 URL 地址: Main.java 文件 */ import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://www.runoob.com/html/html-tutorial.html"); System.out.println("URL 是 " + url.toString()); System.out.println("协议是 " + url.getProtocol()); System.out.println("文件名是 " + url.getFile()); System.out.println("主机是 " + url.getHost()); System.out.println("路径是 " + url.getPath()); System.out.println("端口号是 " + url.getPort()); System.out.println("默认端口号是 " + url.getDefaultPort()); } } /* 以上代码运行输出结果为: URL 是 http://www.runoob.com/html/html-tutorial.html 协议是 http 文件名是 /html/html-tutorial.html 主机是 www.runoob.com 路径是 /html/html-tutorial.html 端口号是 -1 默认端口号是 80 */
- Java 实例 – ServerSocket 和 Socket 通信实例
以下实例演示了如何实现客户端发送消息到服务器,服务器接收到消息并读取输出,然后写出到客户端客户端接收到输出。
1、建立服务器端
- 服务器建立通信ServerSocket
- 服务器建立Socket接收客户端连接
- 建立IO输入流读取客户端发送的数据
- 建立IO输出流向客户端发送数据消息
服务器端代码:
/* Server.java 文件 */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8888); System.out.println("启动服务器...."); Socket s = ss.accept(); System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器"); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //读取客户端发送来的消息 String mess = br.readLine(); System.out.println("客户端:"+mess); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bw.write(mess+"\n"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } } } /* 以上代码运行输出结果为: 启动服务器.... */
2、建立客户端
- 创建Socket通信,设置通信服务器的IP和Port
- 建立IO输出流向服务器发送数据消息
- 建立IO输入流读取服务器发送来的数据消息
客户端代码:
/* Client.java 文件 */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1",8888); //构建IO InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); //向服务器端发送一条消息 bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n"); bw.flush(); //读取服务器返回的消息 BufferedReader br = new BufferedReader(new InputStreamReader(is)); String mess = br.readLine(); System.out.println("服务器:"+mess); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /* 以上代码运行输出结果为: 服务器:测试客户端和服务器通信,服务器接收到消息返回到客户端 */
Java 线程
- Java 实例 – 查看线程是否存活
/* 以下实例演示了如何通过继承 Thread 类并使用 isAlive() 方法来检测一个线程是否存活: TwoThreadAlive.java 文件 */ public class TwoThreadAlive extends Thread { public void run() { for (int i = 0; i < 10; i++) { printMsg(); } } public void printMsg() { Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadAlive tt = new TwoThreadAlive(); tt.setName("Thread"); System.out.println("before start(), tt.isAlive()=" + tt.isAlive()); tt.start(); System.out.println("just after start(), tt.isAlive()=" + tt.isAlive()); for (int i = 0; i < 10; i++) { tt.printMsg(); } System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive()); } } /* 以上代码运行输出结果为: before start(), tt.isAlive()=false just after start(), tt.isAlive()=true name=main name=Thread name=main name=main name=main name=main name=main name=main name=main name=main name=main name=Thread name=Thread name=Thread name=Thread name=Thread The end of main(), tt.isAlive()=true name=Thread name=Thread name=Thread name=Thread */
- Java 实例 – 获取当前线程名称
/* 以下实例演示了如何通过继承 Thread 类并使用 getName() 方法来获取当前线程名称: TwoThreadGetName.java 文件 */ public class TwoThreadGetName extends Thread { public void run() { for (int i = 0; i < 10; i++) { printMsg(); } } public void printMsg() { Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadGetName tt = new TwoThreadGetName(); tt.start(); for (int i = 0; i < 10; i++) { tt.printMsg(); } } } /* 以上代码运行输出结果为: name=main name=main name=main name=main name=main name=Thread-0 name=Thread-0 name=Thread-0 name=Thread-0 name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 */
- Java 实例 – 状态监测
/* 以下实例演示了如何通过继承 Thread 类并使用 currentThread.getName() 方法来监测线程的状态: Main.java 文件 */ class MyThread extends Thread{ boolean waiting= true; boolean ready= false; MyThread() { } public void run() { String thrdName = Thread.currentThread().getName(); System.out.println(thrdName + " starting."); while(waiting) System.out.println("waiting:"+waiting); System.out.println("waiting..."); startWait(); try { Thread.sleep(1000); } catch(Exception exc) { System.out.println(thrdName + " interrupted."); } System.out.println(thrdName + " terminating."); } synchronized void startWait() { try { while(!ready) wait(); } catch(InterruptedException exc) { System.out.println("wait() interrupted"); } } synchronized void notice() { ready = true; notify(); } } public class Main { public static void main(String args[]) throws Exception{ MyThread thrd = new MyThread(); thrd.setName("MyThread #1"); showThreadStatus(thrd); thrd.start(); Thread.sleep(50); showThreadStatus(thrd); thrd.waiting = false; Thread.sleep(50); showThreadStatus(thrd); thrd.notice(); Thread.sleep(50); showThreadStatus(thrd); while(thrd.isAlive()) System.out.println("alive"); showThreadStatus(thrd); } static void showThreadStatus(Thread thrd) { System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState()); } } /* 以上代码运行输出结果为: …… alive alive MyThread #1 terminating. alive …… */
- Java 实例 – 线程优先级设置
/* 以下实例演示了如何通过setPriority() 方法来设置线程的优先级: * SimplePriorities.java 文件 */ public class SimplePriorities extends Thread { private int countDown = 5; private volatile double d = 0; public SimplePriorities(int priority) { setPriority(priority); start(); } public String toString() { return super.toString() + ": " + countDown; } public void run() { while(true) { for(int i = 1; i < 100000; i++) d = d + (Math.PI + Math.E) / (double)i; System.out.println(this); if(--countDown == 0) return; } } public static void main(String[] args) { new SimplePriorities(Thread.MAX_PRIORITY); for(int i = 0; i < 5; i++) new SimplePriorities(Thread.MIN_PRIORITY); } } /* 以上代码运行输出结果为: Thread[Thread-1,1,main]: 5 Thread[Thread-2,1,main]: 5 Thread[Thread-3,1,main]: 5 Thread[Thread-0,10,main]: 5 Thread[Thread-3,1,main]: 4 Thread[Thread-0,10,main]: 4 Thread[Thread-1,1,main]: 4 Thread[Thread-5,1,main]: 5 Thread[Thread-4,1,main]: 5 Thread[Thread-2,1,main]: 4 Thread[Thread-0,10,main]: 3 Thread[Thread-1,1,main]: 3 Thread[Thread-4,1,main]: 4 Thread[Thread-2,1,main]: 3 …… */
- Java 实例 – 死锁及解决方法
死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不可能正常终止。
java 死锁产生的四个必要条件:
1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
2、不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
3、请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
4、循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。当上述四个条件都成立的时候,便形成死锁。当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。下面用java代码来模拟一下死锁的产生。 解决死锁问题的方法是:一种是用 synchronized,一种是用 Lock 显式锁实现。 而如果不恰当的使用了锁,且出现同时要锁多个对象时,会出现死锁情况,如下:
/* LockTest.java 文件 */ import java.util.Date; public class LockTest { public static String obj1 = "obj1"; public static String obj2 = "obj2"; public static void main(String[] args) { LockA la = new LockA(); new Thread(la).start(); LockB lb = new LockB(); new Thread(lb).start(); } } class LockA implements Runnable{ public void run() { try { System.out.println(new Date().toString() + " LockA 开始执行"); while(true){ synchronized (LockTest.obj1) { System.out.println(new Date().toString() + " LockA 锁住 obj1"); Thread.sleep(3000); // 此处等待是给B能锁住机会 synchronized (LockTest.obj2) { System.out.println(new Date().toString() + " LockA 锁住 obj2"); Thread.sleep(60 * 1000); // 为测试,占用了就不放 } } } } catch (Exception e) { e.printStackTrace(); } } } class LockB implements Runnable{ public void run() { try { System.out.println(new Date().toString() + " LockB 开始执行"); while(true){ synchronized (LockTest.obj2) { System.out.println(new Date().toString() + " LockB 锁住 obj2"); Thread.sleep(3000); // 此处等待是给A能锁住机会 synchronized (LockTest.obj1) { System.out.println(new Date().toString() + " LockB 锁住 obj1"); Thread.sleep(60 * 1000); // 为测试,占用了就不放 } } } } catch (Exception e) { e.printStackTrace(); } } } /* 以上代码运行输出结果为: Tue May 05 10:51:06 CST 2015 LockB 开始执行 Tue May 05 10:51:06 CST 2015 LockA 开始执行 Tue May 05 10:51:06 CST 2015 LockB 锁住 obj2 Tue May 05 10:51:06 CST 2015 LockA 锁住 obj1 */
此时死锁产生。
为了解决这个问题,我们不使用显示的去锁,我们用信号量去控制。
信号量可以控制资源能被多少线程访问,这里我们指定只能被一个线程访问,就做到了类似锁住。而信号量可以指定去获取的超时时间,我们可以根据这个超时时间,去做一个额外处理。
对于无法成功获取的情况,一般就是重复尝试,或指定尝试的次数,也可以马上退出。
来看下如下代码:
/* UnLockTest.java 文件 */ import java.util.Date; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class UnLockTest { public static String obj1 = "obj1"; public static final Semaphore a1 = new Semaphore(1); public static String obj2 = "obj2"; public static final Semaphore a2 = new Semaphore(1); public static void main(String[] args) { LockAa la = new LockAa(); new Thread(la).start(); LockBb lb = new LockBb(); new Thread(lb).start(); } } class LockAa implements Runnable { public void run() { try { System.out.println(new Date().toString() + " LockA 开始执行"); while (true) { if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockA 锁住 obj1"); if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockA 锁住 obj2"); Thread.sleep(60 * 1000); // do something }else{ System.out.println(new Date().toString() + "LockA 锁 obj2 失败"); } }else{ System.out.println(new Date().toString() + "LockA 锁 obj1 失败"); } UnLockTest.a1.release(); // 释放 UnLockTest.a2.release(); Thread.sleep(1000); // 马上进行尝试,现实情况下do something是不确定的 } } catch (Exception e) { e.printStackTrace(); } } } class LockBb implements Runnable { public void run() { try { System.out.println(new Date().toString() + " LockB 开始执行"); while (true) { if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockB 锁住 obj2"); if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockB 锁住 obj1"); Thread.sleep(60 * 1000); // do something }else{ System.out.println(new Date().toString() + "LockB 锁 obj1 失败"); } }else{ System.out.println(new Date().toString() + "LockB 锁 obj2 失败"); } UnLockTest.a1.release(); // 释放 UnLockTest.a2.release(); Thread.sleep(10 * 1000); // 这里只是为了演示,所以tryAcquire只用1秒,而且B要给A让出能执行的时间,否则两个永远是死锁 } } catch (Exception e) { e.printStackTrace(); } } } /* 以上实例代码输出结构为: Tue May 05 10:59:13 CST 2015 LockA 开始执行 Tue May 05 10:59:13 CST 2015 LockB 开始执行 Tue May 05 10:59:13 CST 2015 LockB 锁住 obj2 Tue May 05 10:59:13 CST 2015 LockA 锁住 obj1 Tue May 05 10:59:14 CST 2015LockB 锁 obj1 失败 Tue May 05 10:59:14 CST 2015LockA 锁 obj2 失败 Tue May 05 10:59:15 CST 2015 LockA 锁住 obj1 Tue May 05 10:59:15 CST 2015 LockA 锁住 obj2 */
- Java 实例 – 获取线程id
/* 以下实例演示了如何使用 getThreadId() 方法获取线程id: Main.java 文件 */ public class Main extends Object implements Runnable { private ThreadID var; public Main(ThreadID v) { this.var = v; } public void run() { try { print("var getThreadID =" + var.getThreadID()); Thread.sleep(2000); print("var getThreadID =" + var.getThreadID()); } catch (InterruptedException x) { } } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg); } public static void main(String[] args) { ThreadID tid = new ThreadID(); Main shared = new Main(tid); try { Thread threadA = new Thread(shared, "threadA"); threadA.start(); Thread.sleep(500); Thread threadB = new Thread(shared, "threadB"); threadB.start(); Thread.sleep(500); Thread threadC = new Thread(shared, "threadC"); threadC.start(); } catch (InterruptedException x) { } } } class ThreadID extends ThreadLocal { private int nextID; public ThreadID() { nextID = 10001; } private synchronized Integer getNewID() { Integer id = new Integer(nextID); nextID++; return id; } protected Object initialValue() { print("in initialValue()"); return getNewID(); } public int getThreadID() { Integer id = (Integer) get(); return id.intValue(); } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg); } } /* 以上代码运行输出结果为: threadA: in initialValue() threadA: var getThreadID =10001 threadB: in initialValue() threadB: var getThreadID =10002 threadC: in initialValue() threadC: var getThreadID =10003 threadA: var getThreadID =10001 threadB: var getThreadID =10002 threadC: var getThreadID =10003 */
- Java 实例 – 线程挂起
/* 以下实例演示了如何将线程挂起: SleepingThread.java 文件 */ public class SleepingThread extends Thread { private int countDown = 5; private static int threadCount = 0; public SleepingThread() { super("" + ++threadCount); start(); } public String toString() { return "#" + getName() + ": " + countDown; } public void run() { while (true) { System.out.println(this); if (--countDown == 0) return; try { sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 5; i++) new SleepingThread().join(); System.out.println("线程已被挂起"); } } /* 以上代码运行输出结果为: #1: 5 #1: 4 #1: 3 #1: 2 #1: 1 …… #5: 3 #5: 2 #5: 1 线程已被挂起 */
- Java 实例 – 终止线程
Java中原来在Thread中提供了stop()方法来终止线程,但这个方法是不安全的,所以一般不建议使用。 本文向大家介绍使用interrupt方法中断线程。
使用interrupt方法来终端线程可分为两种情况:
(1)线程处于阻塞状态,如使用了sleep方法。
(2)使用while(!isInterrupted()){……}来判断线程是否被中断。在第一种情况下使用 interrupt 方法,sleep 方法将抛出一个 InterruptedException 例外,而在第二种情况下线程将直接退出。下面的代码演示了在第一种情况下使用 interrupt 方法。
/* ThreadInterrupt.java 文件 */ public class ThreadInterrupt extends Thread { public void run() { try { sleep(50000); // 延迟50秒 } catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); System.out.println("在50秒之内按任意键中断线程!"); System.in.read(); thread.interrupt(); thread.join(); System.out.println("线程已经退出!"); } } /* 以上代码运行输出结果为: 在50秒之内按任意键中断线程! sleep interrupted 线程已经退出! */
- Java 实例 – 生产者/消费者问题
生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,如下图所示,生产者向空间里存放数据,而消费者取用数据,如果不加以协调可能会出现以下情况: 存储空间已满,而生产者占用着它,消费者等着生产者让出空间从而去除产品,生产者等着消费者消费产品,从而向空间中添加产品。互相等待,从而发生死锁。
以下实例演示了如何通过线程解决生产者/消费者问题:
/* author by w3cschool.cc ProducerConsumerTest.java */ public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } } class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("消费者 #" + this.number+ " got: " + value); } } } class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("生产者 #" + this.number + " put: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } } /* 以上代码运行输出结果为: 消费者 #1 got: 0 生产者 #1 put: 0 生产者 #1 put: 1 消费者 #1 got: 1 生产者 #1 put: 2 消费者 #1 got: 2 生产者 #1 put: 3 消费者 #1 got: 3 生产者 #1 put: 4 消费者 #1 got: 4 生产者 #1 put: 5 消费者 #1 got: 5 生产者 #1 put: 6 消费者 #1 got: 6 生产者 #1 put: 7 消费者 #1 got: 7 生产者 #1 put: 8 消费者 #1 got: 8 生产者 #1 put: 9 消费者 #1 got: 9 */
- Java 实例 – 状态监测
/* 以下实例演示了如何通过继承 Thread 类并使用 currentThread.getName() 方法来监测线程的状态: Main.java 文件 */ class MyThread extends Thread{ boolean waiting= true; boolean ready= false; MyThread() { } public void run() { String thrdName = Thread.currentThread().getName(); System.out.println(thrdName + " starting."); while(waiting) System.out.println("waiting:"+waiting); System.out.println("waiting..."); startWait(); try { Thread.sleep(1000); } catch(Exception exc) { System.out.println(thrdName + " interrupted."); } System.out.println(thrdName + " terminating."); } synchronized void startWait() { try { while(!ready) wait(); } catch(InterruptedException exc) { System.out.println("wait() interrupted"); } } synchronized void notice() { ready = true; notify(); } } public class Main { public static void main(String args[]) throws Exception{ MyThread thrd = new MyThread(); thrd.setName("MyThread #1"); showThreadStatus(thrd); thrd.start(); Thread.sleep(50); showThreadStatus(thrd); thrd.waiting = false; Thread.sleep(50); showThreadStatus(thrd); thrd.notice(); Thread.sleep(50); showThreadStatus(thrd); while(thrd.isAlive()) System.out.println("alive"); showThreadStatus(thrd); } static void showThreadStatus(Thread thrd) { System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState()); } } /* 以上代码运行输出结果为: …… alive alive MyThread #1 terminating. alive …… */
- Java 实例 – 线程优先级设置
/* 以下实例演示了如何通过setPriority() 方法来设置线程的优先级: SimplePriorities.java 文件 */ public class SimplePriorities extends Thread { private int countDown = 5; private volatile double d = 0; public SimplePriorities(int priority) { setPriority(priority); start(); } public String toString() { return super.toString() + ": " + countDown; } public void run() { while(true) { for(int i = 1; i < 100000; i++) d = d + (Math.PI + Math.E) / (double)i; System.out.println(this); if(--countDown == 0) return; } } public static void main(String[] args) { new SimplePriorities(Thread.MAX_PRIORITY); for(int i = 0; i < 5; i++) new SimplePriorities(Thread.MIN_PRIORITY); } } /* 以上代码运行输出结果为: Thread[Thread-1,1,main]: 5 Thread[Thread-2,1,main]: 5 Thread[Thread-3,1,main]: 5 Thread[Thread-0,10,main]: 5 Thread[Thread-3,1,main]: 4 Thread[Thread-0,10,main]: 4 Thread[Thread-1,1,main]: 4 Thread[Thread-5,1,main]: 5 Thread[Thread-4,1,main]: 5 Thread[Thread-2,1,main]: 4 Thread[Thread-0,10,main]: 3 Thread[Thread-1,1,main]: 3 Thread[Thread-4,1,main]: 4 Thread[Thread-2,1,main]: 3 …… */
- Java 实例 – 死锁及解决方法
死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不可能正常终止。
java 死锁产生的四个必要条件:
1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
2、不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
3、请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
4、循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。当上述四个条件都成立的时候,便形成死锁。当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。下面用java代码来模拟一下死锁的产生。 解决死锁问题的方法是:一种是用 synchronized,一种是用 Lock 显式锁实现。 而如果不恰当的使用了锁,且出现同时要锁多个对象时,会出现死锁情况,如下:
/* LockTest.java 文件 */ import java.util.Date; public class LockTest { public static String obj1 = "obj1"; public static String obj2 = "obj2"; public static void main(String[] args) { LockA la = new LockA(); new Thread(la).start(); LockB lb = new LockB(); new Thread(lb).start(); } } class LockA implements Runnable{ public void run() { try { System.out.println(new Date().toString() + " LockA 开始执行"); while(true){ synchronized (LockTest.obj1) { System.out.println(new Date().toString() + " LockA 锁住 obj1"); Thread.sleep(3000); // 此处等待是给B能锁住机会 synchronized (LockTest.obj2) { System.out.println(new Date().toString() + " LockA 锁住 obj2"); Thread.sleep(60 * 1000); // 为测试,占用了就不放 } } } } catch (Exception e) { e.printStackTrace(); } } } class LockB implements Runnable{ public void run() { try { System.out.println(new Date().toString() + " LockB 开始执行"); while(true){ synchronized (LockTest.obj2) { System.out.println(new Date().toString() + " LockB 锁住 obj2"); Thread.sleep(3000); // 此处等待是给A能锁住机会 synchronized (LockTest.obj1) { System.out.println(new Date().toString() + " LockB 锁住 obj1"); Thread.sleep(60 * 1000); // 为测试,占用了就不放 } } } } catch (Exception e) { e.printStackTrace(); } } } /* 以上代码运行输出结果为: Tue May 05 10:51:06 CST 2015 LockB 开始执行 Tue May 05 10:51:06 CST 2015 LockA 开始执行 Tue May 05 10:51:06 CST 2015 LockB 锁住 obj2 Tue May 05 10:51:06 CST 2015 LockA 锁住 obj1 */
此时死锁产生。
为了解决这个问题,我们不使用显示的去锁,我们用信号量去控制。
信号量可以控制资源能被多少线程访问,这里我们指定只能被一个线程访问,就做到了类似锁住。而信号量可以指定去获取的超时时间,我们可以根据这个超时时间,去做一个额外处理。
对于无法成功获取的情况,一般就是重复尝试,或指定尝试的次数,也可以马上退出。
来看下如下代码:
/* UnLockTest.java 文件 */ import java.util.Date; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class UnLockTest { public static String obj1 = "obj1"; public static final Semaphore a1 = new Semaphore(1); public static String obj2 = "obj2"; public static final Semaphore a2 = new Semaphore(1); public static void main(String[] args) { LockAa la = new LockAa(); new Thread(la).start(); LockBb lb = new LockBb(); new Thread(lb).start(); } } class LockAa implements Runnable { public void run() { try { System.out.println(new Date().toString() + " LockA 开始执行"); while (true) { if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockA 锁住 obj1"); if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockA 锁住 obj2"); Thread.sleep(60 * 1000); // do something }else{ System.out.println(new Date().toString() + "LockA 锁 obj2 失败"); } }else{ System.out.println(new Date().toString() + "LockA 锁 obj1 失败"); } UnLockTest.a1.release(); // 释放 UnLockTest.a2.release(); Thread.sleep(1000); // 马上进行尝试,现实情况下do something是不确定的 } } catch (Exception e) { e.printStackTrace(); } } } class LockBb implements Runnable { public void run() { try { System.out.println(new Date().toString() + " LockB 开始执行"); while (true) { if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockB 锁住 obj2"); if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) { System.out.println(new Date().toString() + " LockB 锁住 obj1"); Thread.sleep(60 * 1000); // do something }else{ System.out.println(new Date().toString() + "LockB 锁 obj1 失败"); } }else{ System.out.println(new Date().toString() + "LockB 锁 obj2 失败"); } UnLockTest.a1.release(); // 释放 UnLockTest.a2.release(); Thread.sleep(10 * 1000); // 这里只是为了演示,所以tryAcquire只用1秒,而且B要给A让出能执行的时间,否则两个永远是死锁 } } catch (Exception e) { e.printStackTrace(); } } } /* 以上实例代码输出结构为: Tue May 05 10:59:13 CST 2015 LockA 开始执行 Tue May 05 10:59:13 CST 2015 LockB 开始执行 Tue May 05 10:59:13 CST 2015 LockB 锁住 obj2 Tue May 05 10:59:13 CST 2015 LockA 锁住 obj1 Tue May 05 10:59:14 CST 2015LockB 锁 obj1 失败 Tue May 05 10:59:14 CST 2015LockA 锁 obj2 失败 Tue May 05 10:59:15 CST 2015 LockA 锁住 obj1 Tue May 05 10:59:15 CST 2015 LockA 锁住 obj2 */
- Java 实例 – 获取线程状态
Java中的线程的生命周期大体可分为5种状态。
- 1. 新建状态(New):新创建了一个线程对象。
- 2. 就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法。该状态的线程位于可运行线程池中,变得可运行,等待获取CPU的使用权。
- 3. 运行状态(Running):就绪状态的线程获取了CPU,执行程序代码。
- 4. 阻塞状态(Blocked):阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:
- (一)、等待阻塞:运行的线程执行wait()方法,JVM会把该线程放入等待池中。
- (二)、同步阻塞:运行的线程在获取对象的同步锁时,若该同步锁被别的线程占用,则JVM会把该线程放入锁池中。
- (三)、其他阻塞:运行的线程执行sleep()或join()方法,或者发出了I/O请求时,JVM会把该线程置为阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
- 5. 死亡状态(Dead):线程执行完了或者因异常退出了run()方法,该线程结束生命周期。
以下实例演示了如何获取线程的状态:
/* 以下实例演示了如何获取线程的状态: Main.java 文件 */ class MyThread extends Thread{ boolean waiting= true; boolean ready= false; MyThread() { } public void run() { String thrdName = Thread.currentThread().getName(); System.out.println(thrdName + " 启动"); while(waiting) System.out.println("等待:"+waiting); System.out.println("等待..."); startWait(); try { Thread.sleep(1000); } catch(Exception exc) { System.out.println(thrdName + " 中断。"); } System.out.println(thrdName + " 结束。"); } synchronized void startWait() { try { while(!ready) wait(); } catch(InterruptedException exc) { System.out.println("wait() 中断。"); } } synchronized void notice() { ready = true; notify(); } } public class Main { public static void main(String args[]) throws Exception{ MyThread thrd = new MyThread(); thrd.setName("MyThread #1"); showThreadStatus(thrd); thrd.start(); Thread.sleep(50); showThreadStatus(thrd); thrd.waiting = false; Thread.sleep(50); showThreadStatus(thrd); thrd.notice(); Thread.sleep(50); showThreadStatus(thrd); while(thrd.isAlive()) { System.out.println("alive"); } showThreadStatus(thrd); } static void showThreadStatus(Thread thrd) { System.out.println(thrd.getName()+" 存活:" +thrd.isAlive()+" 状态:" + thrd.getState() ); } } /* 以上代码运行输出结果为: …… alive alive alive MyThread #1 结束。 alive alive alive alive alive alive alive MyThread #1 存活:false 状态:TERMINATED */
- Java 实例 – 获取所有线程
/* 以下实例演示了如何使用 getName() 方法获取所有正在运行的线程: * Main.java 文件 */ public class Main extends Thread { public static void main(String[] args) { Main t1 = new Main(); t1.setName("thread1"); t1.start(); ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int noThreads = currentGroup.activeCount(); Thread[] lstThreads = new Thread[noThreads]; currentGroup.enumerate(lstThreads); for (int i = 0; i < noThreads; i++) System.out.println("线程号:" + i + " = " + lstThreads[i].getName()); } } /* 以上代码运行输出结果为: 线程号:0 = main 线程号:1 = thread1 */
- Java 实例 – 查看线程优先级
/* 以下实例演示了如何使用 getThreadId() 方法获取线程id: * Main.java 文件 */ public class Main extends Object { private static Runnable makeRunnable() { Runnable r = new Runnable() { public void run() { for (int i = 0; i < 5; i++) { Thread t = Thread.currentThread(); System.out.println("in run() - priority=" + t.getPriority()+ ", name=" + t.getName()); try { Thread.sleep(2000); } catch (InterruptedException x) { } } } }; return r; } public static void main(String[] args) { System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority()); System.out.println("in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName()); Thread threadA = new Thread(makeRunnable(), "threadA"); threadA.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("in main() - threadA.getPriority()="+ threadA.getPriority()); } } /* 以上代码运行输出结果为: in main() - Thread.currentThread().getPriority()=5 in main() - Thread.currentThread().getName()=main in run() - priority=5, name=threadA in run() - priority=5, name=threadA in main() - threadA.getPriority()=5 in run() - priority=5, name=threadA in run() - priority=5, name=threadA in run() - priority=5, name=threadA */
- Java 实例 – 中断线程
/* 以下实例演示了如何使用interrupt()方法来中断线程并使用 isInterrupted() 方法来判断线程是否已中断: Main.java 文件 */ public class Main extends Object implements Runnable { public void run() { try { System.out.println("in run() - 将运行 work2() 方法"); work2(); System.out.println("in run() - 从 work2() 方法回来"); } catch (InterruptedException x) { System.out.println("in run() - 中断 work2() 方法"); return; } System.out.println("in run() - 休眠后执行"); System.out.println("in run() - 正常离开"); } public void work2() throws InterruptedException { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted()); Thread.sleep(2000); System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted()); } } } public void work() throws InterruptedException { while (true) { for (int i = 0; i < 100000; i++) { int j = i * 2; } System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted()); if (Thread.interrupted()) { System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted()); throw new InterruptedException(); } } } public static void main(String[] args) { Main si = new Main(); Thread t = new Thread(si); t.start(); try { Thread.sleep(2000); } catch (InterruptedException x) { } System.out.println("in main() - 中断其他线程"); t.interrupt(); System.out.println("in main() - 离开"); } } /* 以上代码运行输出结果为: in run() - 将运行 work2() 方法 in main() - 中断其他线程 in main() - 离开 C isInterrupted()=true in run() - 中断 work2() 方法 */