java容器set与Array互相转换的例子
/*********************************************************function:set and array Convert each other with java sample file :setAndArray.javaauthor :chinayaosir QQ:44633197Tools :MyEclipse Versi
/*********************************************************
function:set and array Convert each other with java sample
file :setAndArray.java
author :chinayaosir QQ:44633197
Tools :MyEclipse Version: 6.0.1 GA
date :10/26/2010
blog :http://blog.csdn.net/chinayaosir
note :禁止其它网站转载此文章
*********************************************************/
import java.util.*;
public class setAndArray {
public static void main(String[] args) {
listToSet();
arrayListToHashSet();
setToArray1();
setToArray2();
}
public static void listToSet() {
List<String> myList = new ArrayList<String>();
myList.add("AA ");
myList.add("BB ");
myList.add("CC ");
myList.add("DD ");
Set<String> mySet = new HashSet<String>(myList);
System.out.println("listToSet");
for (Object theFruit : mySet)
{System.out.print(theFruit);}
System.out.println(" ");
}
public static void arrayListToHashSet() {
List<String> myList = new ArrayList<String>();
myList.add("AA ");
myList.add("BB ");
myList.add("CC ");
myList.add("DD ");
Set<String> mySet = new HashSet<String>(myList);
System.out.println("arrayListToHashSet");
for (Object theFruit : mySet)
{System.out.print(theFruit);}
System.out.println(" ");
}
public static void setToArray1(){
//set create and set some value
Set<String> set = new TreeSet<String>();
set.add("bb ");
set.add("cc ");
set.add("aa ");
//create array with set.size,then get value from set
String[] array = (String[]) set.toArray(new String[set.size()]);
Arrays.toString(array);
System.out.println("setToArray");
for (Object theFruit : array)
{System.out.print(theFruit);}
System.out.println(" ");
}
public static void setToArray2(){
//set create and set different data type value
Set<Object> set = new HashSet<Object>();
set.add("A "); //string
set.add(new Long(10)); //long
set.add(new Date()); //date
//create list with set,list save into Objects array
List<Object> list = new ArrayList<Object>(set);
Object[] objects = list.toArray();
System.out.println("SetToArray With different datatype");
for (int i = 0; i < objects.length; i++) {
Object object = objects[i];
System.out.println("Object = " + object);
}
}
}
/*code run value ,pls see below
listToSet
AA BB CC DD
arrayListToHashSet
AA BB CC DD
setToArray
aa bb cc
SetToArray With different datatype
Object = Tue Oct 26 11:18:19 CST 2010
Object = A
Object = 10
*
**/
更多推荐
所有评论(0)