------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
集合
一.java集合概述
面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象。java集合分为分为Collection和Map两种体系。
2.Collection接口的子接口List:
2.1.ArrayList:底层数据结构是数组结构,线程不安全,查询速度快。2.2.LinkedList:底层数据结构是链表结构,增删速度快。2.3.Vector:线程安全,但速度慢,已被ArrayList替代。
</pre><pre name="code" class="html">import java.util.*;
class ListDemo
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
List a1=new ArrayList();
a1.add("java01");
a1.add("java02");
a1.add("java03");
Iterator it=a1.iterator();
while(it.hasNext())
{
sop("next:"+it.next());
}
}
}
迭代器使用注意事项:
迭代器在Collcection接口中是通用的,它替代了Vector类中的Enumeration(枚举)。迭代器的next方法是自动向下取元素,要避免出现NoSuchElementException。迭代器的next方法返回值类型是Object,所以要记得类型转换。List集合判断元素是否相同的依据是元素的equals方法。
3.Collection接口的子接口Set:
3.1HashSet
不能保证元素的排列顺序,HashSet 不是线程安全的,集合元素可以是null。
例:两个对象通过hashCode() 方法比较相等,并且两个对象的equals()方法返回值也相等。
import java.util.*; class HashSetTest { public static void main(String[] args) { HashSet hs=new HashSet(); hs.add(new Person("a1",11)); hs.add(new Person("a2",12)); hs.add(new Person("a3",13)); hs.add(new Person("a2",12)); //hs.add(new Person("a4",14)); Iterator it=hs.iterator(); while (it.hasNext()) { Person p=(Person)it.next(); sop(p.getName()+"..."+p.getAge()); } } public static void sop(Object obj) { System.out.println(obj); } } class Person { private String name; private int age; Person(String name,int age) { this.name=name; this.age=age; } public String getName() { return name; } public int getAge() { return age; } public int hashCode() { return 60; } public boolean equals(Object obj) { if(!(obj instanceof Person)) return false; Person p=(Person)obj; return this.name.equals(p.name)&&this.age==age; } }
3.2TreeSet
通过compareTo或者compare方法中的来保证元素的唯一性。元素是以二叉树的形式存放的。
import java.util.*;
class TreeSetTest
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet(new StrLenCompare());
ts.add("abcdef");
ts.add("vbcdf");
ts.add("a");
ts.add("abc");
ts.add("adc");
ts.add("ab");
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class StrLenCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
/*
if (s1.length()>s2.length())
{
return 1;
}
if(s1.length()==s2.length())
return 0;
return -1;*/
int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0)
return s1.compareTo(s2);
return num;
}
}
三泛型
为什么需要泛型?
1. 解决元素存储的安全性问题
2. 解决获取数据元素时,需要类型强转的问题
泛型的特点:
1.提高了程序的安全性
2.将运行期遇到的问题转移到了编译期
3.省去了类型强转的麻烦
4.泛型类的出现优化了程序设计
泛型的使用:
1.泛型的声明
interfaceList<T> 和classTestGen<K,V>
其中,T,K,V不代表值,而是表示类型。这里使用任意字母都可以。常用T表示,是Type的缩写。
2.泛型的实例化:
一定要在类名后面指定类型参数的值(类型)。如:
List<String> strList = new ArrayList<String>();
Iterator<Customer>iterator = customers.iterator();