collections 集合基础用法
包括ArrayList,LinkedList, HashSet, TreeSet, HashMap, Stack,Queue,PriorityQueue的方法和用法。
上代码:
package com.yuxin.learn;
import java.util.*;
public class Main {
private static void display(Iterator<String> it) {
System.out.println("call display():");
// TODO Auto-generated method stub
while(it.hasNext()){
String s = it.next();
System.out.print(s+" ");
}
System.out.println();
}
public static void print(Object l){
System.out.println(l);
}
public static void main(String[] args){
/**
* 1. List Set Queue 继承自Collection
*(1).ArrayList继承自List
*1) ArrayList的所有方法
*/
Collection<Integer> alt_Int = new ArrayList<Integer>();
alt_Int.add(0);
alt_Int.add(2);
Random rand = new Random();
for(int i=1;i<100;i++){
alt_Int.add(rand.nextInt(30));
}
System.out.println(alt_Int);
/**
* 1. List Set Queue 继承自Collection
*(1).ArrayList继承自List
*1) ArrayList的所有方法
*/
//List<String> altString = Arrays.asList("dog","cat","pig");
print("**************** Part 1 ArrayList Method ***********");
ArrayList<String> altString = new ArrayList<String>();
altString.add("dog");
altString.add("cat");
altString.add("pig");
print("1 pets:"+ altString);
altString.add("rat");
print("2 add rat:"+ altString);
// a.contiains(b)
print("3 contains rat?:"+altString.contains("rat"));
ArrayList<pet> altObj = new ArrayList<pet>();
pet p1 = new pet("objcat");
altObj.add(p1);
pet p2 = new pet("objdog");
altObj.add(p2);
//add()
print("4 objcat indexof:"+altObj.indexOf(p1));
pet p3 = new pet("obj3");
altObj.add(p3);
pet p4 = new pet("obj4");
altObj.add(p4);
pet p5 = new pet("obj5");
altObj.add(p5);
print ("5 objArrayList:"+altObj);
//subList()
List<pet> sub = altObj.subList(2, 5);
print("6 sub Arraylist:"+sub);
//containsAll()
print("7 containsAll: "+ altObj.containsAll(sub));
Collections.shuffle(sub,rand);
print("8 shuffle sub Arraylist:"+sub);
List<pet> sub2 = new ArrayList<pet>();
//asList()
sub2=Arrays.asList(altObj.get(1),altObj.get(3));
print("9 .get sub: "+ sub2);
List<pet> temp = new ArrayList<pet>();
temp = altObj;
//a.removeAll(b)
print("10 before removeAll: "+temp);
temp.removeAll(sub2);
print("11 after removeAll in sub2:"+temp);
//a.clear()
temp.clear();
print("12 after clear:"+temp);
//a.isEmpty()
print("13 isEmpty():"+temp.isEmpty());
Object[] o = altObj.toArray();
print("14 toArray():"+o);
//iterator
Iterator<pet> it = altObj.iterator();
print("15 iterator: ");
while(it.hasNext()){
pet p = it.next();
System.out.print(p+". ");
}
print(" ");
display(altString.iterator());
print("**************** Part 2 LinkList Method ***********");
LinkedList<String> objLinkList = new LinkedList<String>(Arrays.asList("cat","rat","dot","bird","ant"));
print("1 objLinkList:"+objLinkList);
//getFirst()
print("2 getFist():"+objLinkList.getFirst());
//element()
print("3 element():"+objLinkList.element());
//peek()
print("4 peek()"+objLinkList.peek());
//remove()
//String r = objLinkList.element();
//objLinkList.remove(r);
print("5 remove()"+objLinkList.remove());
//LinkedList<String> ListTemp = objLinkList;
//removeFirst()
print("6 removeFirst():"+objLinkList.removeFirst());
print("7 after remove"+objLinkList);
//addFirst()
objLinkList.addFirst("Rat");
print("8 after addFist():"+objLinkList);
//offer()
objLinkList.offer("OfferA");
print("9 after offer():"+objLinkList);
//addLast
objLinkList.addLast("AddLastB");
print("10 after addLast:"+objLinkList);
objLinkList.removeLast();
print("10 after removeLast:"+objLinkList);
print("**************** Part 3 Stack Method ***********");
//print("Impement a Stack using LinkedList:");
Stack<String> stk = new Stack<String>();
String str = "I Love Java progaraming!";
print("store sentence \"I Love Java progaraming!\" in a stack and pop out:");
for(String s:str.split(" ")){
stk.push(s);
}
while(!stk.isEmpty()) print( stk.pop()+" ");
System.out.println();
print("**************** Part 4 Set Method ***********");
/**
* Set 不保存重复元素
* 可以选择HashSet或者TreeSet实现,专门对快速查找进行优化。
* HashSet 保存顺序没有规律(散列存储),TreeSet 红-黑树存储
* LinkedHashSet 使用了散列存储,但使用链表维护元素插入顺序。
*/
Set<String> set1 = new HashSet<String>();
//Collections.addAll()
print("Collections.addAll():");
Collections.addAll(set1, "A B C D E F G H I J K L M".split(" "));
print(set1);
set1.add("N");
//contiains
print("1 contains() H:"+set1.contains("H"));
print("2 contains() Z:"+set1.contains("Z"));
Set<String> set2 = new HashSet<String>();
Collections.addAll(set2, "G H I J".split(" "));
print("3 containsAll() set2 in set1:"+set1.containsAll(set2));
set1.remove("H");
print("4 after remove H whether contains H:"+set1.contains("H"));
print("5 after remove H,set1 containsAll set2?:"+set1.containsAll(set2));
Collections.addAll(set1, "X Y Z".split(" "));
print("6 'X Y Z'added to set1:"+set1);
print("7 TreeSet:");
//rand.nextInt
Set<Integer> altIntSort = new TreeSet<Integer>();
for(int i=1;i<100;i++){
altIntSort.add(rand.nextInt(30));
}
System.out.println(altIntSort);
System.out.println();
print("**************** Part 5 Map Method ***********");
/**
* 用Map求产生的随机数的次数 key->随机数,value->次数
* 1)获得value 用 m.get(key)方法
* 2)存入map 用 m.put(key,value)方法
*/
print("Generate 1000 integer, calculate the frequency.");
Map<Integer,Integer> map1 = new HashMap<Integer,Integer>();
for(int i=0;i<1000;i++){
int r = rand.nextInt(20);
Integer fre = map1.get(r);
map1.put(r,fre==null?1:fre+1);
}
print(map1);
print("hashmap:");
Map<String,String> petMap = new HashMap<String,String>();
petMap.put("yx", "dog");
petMap.put("hx", "cat");
petMap.put("cc", "rat");
//containsKey
print("containsKey: yx:"+petMap.containsKey("yx"));
print("containsKey: yxx:"+petMap.containsKey("yxx"));
print("containsValue: cat:"+petMap.containsValue("cat"));
//keySet
print("keySet:"+petMap.keySet());
//values
print("valueSet:"+petMap.values());
//map<person,List<pet>>;
System.out.println();
print("**************** Part 6 Queue Method ***********");
/**
* 通过将LinkedList向上转型实现Queue.(窄化了LinkedList的访问权限)
* LinkedList提供了方法支持队列的行为,可作为队列的一种实现。
*
*/
Queue<Character> queS = new LinkedList<Character>();
for(char c:"Life is beautiful~".toCharArray()){
queS.offer(c);
}
print("1 String to CharArray offer into queue: "+queS);
//element
print("2 element:"+queS.element());
//peek
print("3 peek:"+queS.peek());
//poll
print("4 poll:"+queS.poll());
print("5 after poll:"+queS);
//addLast
queS.add('*');
print("6 after addLast:"+queS);
print("PriorityQueue:");
/**
*
* 当调用offer()方法添加对象,对象会在队列中被排序
*/
List<String> str1 = Arrays.asList("I think nothing is imporsible".split(" "));
PriorityQueue<String> PriQueS = new PriorityQueue<String>(str1);
print("1 priority que:"+PriQueS);
PriorityQueue<String> PriQueS_reverse = new PriorityQueue<String>(str1.size(),Collections.reverseOrder());
PriQueS_reverse.addAll(str1);
print("2 after add all, priority que _reverse:"+PriQueS_reverse);
String str2 = "I think nothing is imporsible";
List<Character> Allch = new ArrayList<Character>();
for(char c:str2.toCharArray()){
Allch.add(c);
}
PriorityQueue<Character> PriQueAll = new PriorityQueue<Character>();
PriQueAll.addAll(Allch);
print("3 PriorityQueue all char:"+PriQueAll);
//对于字母去重复,注意使用HashSet
Set<Character> charSet = new HashSet<Character>();
for(char c:str2.toCharArray()){
charSet.add(c);
}
PriorityQueue<Character> PriQueC = new PriorityQueue<Character>(charSet);
print("4 PriorityQueue single char:"+PriQueC);
//输出环境变量
Main m =new Main();
EnvironmentVar evn = m.new EnvironmentVar();
evn.output();
print("基本异常");
//Object t1 = null;
//if(t1==null)throw new NullPointerException();
print("如果直接抛出了异常,程序就会停在这,而加入catch后,会继续运行。");
try{
Object t1 = null;
if(t1==null)throw new NullPointerException();
}catch(NullPointerException e){
print("catched a execption!");
}
print("Exception finished");//加入捕捉异常后,才会执行到这
print("**************** Part 7 String Method ***********");
String str0="We are Chinese.";
print("str0"+str0);
//length()
print("1 length:"+str0.length());
//charAt()
print("2 charAt:"+str0.charAt(4));
char[] charArr = new char[20];
for(int i=0;i<20;i++) charArr[i]='0';
//getChars
str0.getChars(3, 7,charArr,4);
for(char c:charArr)System.out.print(c);
System.out.println();
//valueOf
print("3 valueOf(change charArray into String method):"+String.valueOf(charArr));
String str3="Chinese";
print("str3:"+str3);
//equals
print("4 equals:"+str0.equals(str3));
//compareTo
print("5 compareTo:"+str0.compareTo(str3));
//contains
print("6 contains:"+str0.contains(str3));
//StringBuffer
StringBuffer sb = new StringBuffer("We are Chinese.");
//contentEquals
print("7 contentEquals:"+str0.contentEquals(sb));
//equalsIgnoreCase
print("8 equalsIgnoreCase:"+str0.equalsIgnoreCase(str3));
//regionMatches
print("9 regionMatches(区域对比):"+str0.regionMatches(7, str3, 0, 4));
//startsWith
print("10 startsWith:"+str0.startsWith("W"));
//endsWith
print("11 endsWith:"+str0.endsWith("."));
//indexOf
print("12 indexOf(i):"+str0.indexOf("i"));
print("13 indexOf(t):"+str0.indexOf("t"));
//lastIndexOf
print("14 lastIndexOf(i)从后向前搜索:"+str0.lastIndexOf("i"));
//subString
print("15 subString:"+str0.substring(3));
//concat
print("16 concat:"+str0.concat("aaaaaaa"));
//replace
print("17 replace:"+str0.replace("n", "sd"));
//toLowerCase
print("18 toLowerCase:"+str0.toLowerCase());
//toUpperCase
print("19 toUpperCase:"+str0.toUpperCase());
//trim
print("20 trim:"+str0.trim());
//valueOf
/**
* String.valueOf(boolean b) : 将 boolean 变量 b 转换成字符串
String.valueOf(char c) : 将 char 变量 c 转换成字符串
String.valueOf(char[] data) : 将 char 数组 data 转换成字符串
String.valueOf(char[] data, int offset, int count) :
将 char 数组 data 中 由 data[offset] 开始取 count 个元素 转换成字符串
String.valueOf(double d) : 将 double 变量 d 转换成字符串
String.valueOf(float f) : 将 float 变量 f 转换成字符串
String.valueOf(int i) : 将 int 变量 i 转换成字符串
String.valueOf(long l) : 将 long 变量 l 转换成字符串
String.valueOf(Object obj) : 将 obj 对象转换成 字符串, 等于 obj.toString()
*/
print("20 valueOf(转化为字符串):"+String.valueOf(354));
/**
* intern 这个方法 返回字符串对象的规范化表示形式,当调用 intern 方法时
* ,如果池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object)
* 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并且
* 返回此 String 对象的引用。这时候c和d就是相等的。
*/
print("21 intern:判断目前的string对象是否已经存在于常量池,存在则返回存在对象的引用");
String a = "b" ;
String b = "b" ;
System.out.print( a == b);
String c = "d" ;
String d = new String( "d" ).intern() ;
System.out.println( c == d);
String s1 = "ab123" ;
String s2 = new String( "ab123" ) ;
System.out.println( s1 == s2 );
String s3 = s2.intern() ;
System.out.println( s1 == s3 ) ;
int a1=324;
print("格式化输出:");
System.out.printf("a1:%d\n",a1);
System.out.format("a1\\:%d\n",a1);
}
class EnvironmentVar {
/**
* System.getenv()返回一个Map,entrySet()产生一个有Map.Entry的元素构成的Set,
* 并且Set是一个Iterable,因此她可以用于foreach循环。
*/
//public void EnvironmentVar(){}
public void output(){
System.out.println("output environment var:");
for(Map.Entry entry:System.getenv().entrySet()){
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
}
实现上面的代码正常运行,另外还需要一个类:
package com.yuxin.learn;
public class pet{
private String pet;
public pet(String string) {
// TODO Auto-generated constructor stub
pet=string;
}
}