一、为什么不适用数组,而要使用集合类
1、有时候事先无法确定元素的个数
2、有时候需要存取不同类型的对象和数据
而数组只能存取相同数据类型的元素,而且长度是不可变的。
二、Java提供的集合都有哪些:
1、集(Set)
2、列表(List)
3、映射(Map)
Set介绍:不能有重复元素
HashSet类:对元素随机排序的集合类
import java.util.HashSet;
import java.util.Iterator;
public class HashSetTest{
public static void main(String[] args){
HashSet<String> hs = new HashSet<String>();
[color=red]hs.add("red");[/color]
hs.add("yellow");
hs.add("green");
[color=red]hs.add("red");[/color]
System.out.println(hs.size());
System.out.println("hs:"+hs);
Iterator it = hs.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
hs.remove("yellow");
System.out.println("removed hs:"+hs);
int is=hs.size();
System.out.println("hs size:"+is);
Object[] obj = hs.toArray();
for(int i=0; i< obj.length; i++){
System.out.println("obj["+i+"]:"+obj[i]);
}
System.out.println(hs.contains("red"));
System.out.println(hs.contains("orange"));
hs.clear();
System.out.println("cleared hs size:"+hs.size());
System.out.println(hs.isEmpty());
}
}
执行结果:
C:\javastudy>javac HashSetTest.java
C:\javastudy>java HashSetTest
[color=red]3[/color]
hs:[red, green, yellow]
red
green
yellow
removed hs:[red, green]
hs size:2
obj[0]:red
obj[1]:green
true
false
cleared hs size:0
true
C:\javastudy>
1、有时候事先无法确定元素的个数
2、有时候需要存取不同类型的对象和数据
而数组只能存取相同数据类型的元素,而且长度是不可变的。
二、Java提供的集合都有哪些:
1、集(Set)
2、列表(List)
3、映射(Map)
Set介绍:不能有重复元素
HashSet类:对元素随机排序的集合类
import java.util.HashSet;
import java.util.Iterator;
public class HashSetTest{
public static void main(String[] args){
HashSet<String> hs = new HashSet<String>();
[color=red]hs.add("red");[/color]
hs.add("yellow");
hs.add("green");
[color=red]hs.add("red");[/color]
System.out.println(hs.size());
System.out.println("hs:"+hs);
Iterator it = hs.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
hs.remove("yellow");
System.out.println("removed hs:"+hs);
int is=hs.size();
System.out.println("hs size:"+is);
Object[] obj = hs.toArray();
for(int i=0; i< obj.length; i++){
System.out.println("obj["+i+"]:"+obj[i]);
}
System.out.println(hs.contains("red"));
System.out.println(hs.contains("orange"));
hs.clear();
System.out.println("cleared hs size:"+hs.size());
System.out.println(hs.isEmpty());
}
}
执行结果:
C:\javastudy>javac HashSetTest.java
C:\javastudy>java HashSetTest
[color=red]3[/color]
hs:[red, green, yellow]
red
green
yellow
removed hs:[red, green]
hs size:2
obj[0]:red
obj[1]:green
true
false
cleared hs size:0
true
C:\javastudy>