2013年8月15日星期四

Java Note: Java Collections Overview, Set collection (HashSetclass, LinkedHashSet class, TreeSet class, EnumSet class)

 

1.Java Collections Overview
1) An array can hold multiple objects , but the length of the array can not be changed, once the array is specified in the initialization array length, the length of the array is immutable, if you need to save changes in the number of data, the array is a bit powerless; and can not be saved with a mapping between the array data. In order to preserve the number of uncertain data, and the preservation of data mappings, Java provides a collection of classes. Collections primarily responsible for the preservation, dressed other data, so collections also called container classes.
2) Java collection classes can be used to store varying amounts of multiple objects, and can achieve common data structures such as stacks, queues, etc. . Can also be used for the preservation of an associative array mapping relationship. Java collections can be roughly divided into the Set, List, Map three systems, which Set for unordered, unrepeatable collection; List represents an ordered, duplicate collection; Map represents a collection with mappings. Queue system to achieve the collection represents a set of queues.
3) is not the same collection classes and arrays, array elements can be either basic types of values, it can be an object (actually holds the object reference variable); while the collection class can only save the object (actually holds the object reference variable).
4) Java collection classes derive mainly consists of two interfaces: Collection and Map. Set and List interfaces are derived from the Collection interface of the two sub-interfaces, they represent a set of unordered collections and orderly; Queue is the queue implementation provided by Java. Map implementation class used to store data with mapping relationship. Map data is stored for each key-value pairs, which is the key and the value two values. Map where the key is unrepeatable, key is used to identify each item in the collection of data, if you need access to the Map data is always the key to get under the Map.
5) Collection interface is a List, Set, and Queue interfaces parent interface, which can be defined in the method not only for the operation Set collection List collection can also be used to operate and Queue collections.
boolean add (Object o): This method is used to add an element to the collection.
boolean addAll (Collection c): This method is the set of all elements c added to specify the collection.
void clear (): Clear all elements of the collection, the collection length becomes 0.
boolean contains (Object o): returns the collection contains the specified element.
boolean containsAll (Collection c): returns the collection contains all the elements in the collection c.
boolean isEmpty (): returns the collection is empty. When the set length is 0:00 return true, otherwise returns false.
Iterator iterator (): Returns an Iterator object used to traverse the collection elements.
boolean remove (Object o): delete the collection at the specified element o, when the collection contains one or more elements o, these element will be deleted, the method will return true.
boolean removeAll (Collection c): Delete Collection c the collection contains all the elements (equivalent to calling the method with a collection of cut collection c), if you delete one or more elements, the method returns true.
boolean retainAll (Collection c): Delete the collection in the collection does not contain the elements c (equivalent to calling the method set to become The collections of collections intersection c), if the action changes the collection calls the method, the method returns true.
int size (): This method returns the number of elements in the collection.
Object [] toArray (): This method is the collection into an array, all elements of the collection into a corresponding array element.

 

eg:

 
  
package cn.it.lsl; 

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class CollectionTest {
public static void main(String[] args) {
Collection c
= new ArrayList();
c.add(
"小明");
c.add(
6);
System.out.println(
"c集合的元素个数为:"+c.size());
c.remove(
6);
System.out.println(
"c集合的元素个数为:"+c.size());
System.out.println(
"c集合是否包含\"小明\"字符串:"+c.contains("小明"));
c.add(
"JavaEE");
System.out.println(
"c集合的元素:"+c);

Collection books
= new HashSet();
books.add(
"JavaEE");
books.add(
"Android");
System.out.println(
"c集合是否完全包含books集合?"+c.containsAll(books));
c.removeAll(books);
System.out.println(
"c集合的元素:"+c);
c.clear();
System.out.println(
"c集合的元素:"+c);
//books集合里只剩下c集合里也包含的元素
books.retainAll(c);
System.out.println(
"books集合的元素:"+books);

}
}
 
 

6) Iterator interface to traverse the collection elements
Iterator interface is also the Java Collections Framework members, mainly used to traverse the Collection elements in the collection, Iterator objects also called iterators.
Iterator interface is defined in the following three ways:
boolean hasNext (): If the iteration collection element has not been traversed, it returns true.
Object next (): returns the next element in the collection.
void remove (): Remove the collection next method returns the last element.

 

eg:

 
  
package cn.it.lsl; 

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class IteratorTest {
public static void main(String[] args) {
Collection books
= new HashSet();
books.add(
"Java ee");
books.add(
"Java");
books.add(
"Andrroid");
//获取books集合对应的迭代器
Iterator it = books.iterator();
while(it.hasNext()){
//it.next()方法返回的数据类型是Object类型
String book = (String)it.next();
System.out.println(book);
if(book.equals("Java")){
it.remove();
}
book
= "测试字符串";
}
System.out.println(books);
}
}
 
 

Iterator object if you want to create, you must have a collection being iterated.

 
  
package cn.it.lsl; 

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class IteratorTest {
public static void main(String[] args) {
Collection books
= new HashSet();
books.add(
"Java ee");
books.add(
"Java");
books.add(
"Android");
//获取books集合对应的迭代器
Iterator it = books.iterator();
while(it.hasNext()){
//it.next()方法返回的数据类型是Object类型
String book = (String)it.next();
System.out.println(book);
if(book.equals("Android")){
//it.remove();
books.remove(book);
}
//book = "测试字符串";
}
//System.out.println(books);
}
}
 
 

when using Iterator iterate over a Collection collection element, Colleection elements of the collection can not be changed, only through the Iterator's remove method removes the last element before the next method returns a collection can.

 
  
package cn.it.lsl; 

import java.util.Collection;
import java.util.HashSet;

public class ForeachTest {
public static void main(String[] args) {
Collection books
= new HashSet();
books.add(
"Java ee");
books.add(
"Java");
books.add(
"Android");
for(Object obj : books){
String book
= (String)obj;
System.out.println(book);
if(book.equals("Android")){
//以下代码会引发异常
//books.remove(book);
}
}
System.out.println(books);
}
}
 
 

2.Set collection
Set collections and Collection basically exactly the same, It does not provide any additional methods. Is actually Set Collection, just slightly different behavior. (Set not contain duplicate elements).
Set collections may not contain the same elements, if you try to add two of the same elements in the same Set collection, add operation failed.

 
  
package cn.it.lsl; 

import java.util.HashSet;
import java.util.Set;

public class SetTest {
public static void main(String[] args) {
Set books
= new HashSet();
books.add(
new String("java"));
boolean result = books.add(new String("java"));
System.out.println(result
+ "-->" + books);
}
}
 
 

1) HashSet class
(1) HashSet Set interface is implemented . HashSet by Hash algorithm to store elements in the collection, with good access and search performance.
(2) HashSet can not guarantee that the order of the elements, the order may be added in a different order, the order may also change.
(3) When the HashSet collection into one element, HashSet will call the object's hashCode () method to get the object hashCode value, and then according to the HashCode value determines the object is stored in the HashSet. If there are two elements
via equals () method comparison returns true, but their hashCode () method returns the values ​​are not equal, HashSet will store them in different locations, can still successfully added. Namely, HashSet collection to determine whether two elements are equal standards are two objects via equals () method is the same, and the two objects hashCode () method returns a value are equal.

 
  
package cn.it.lsl; 

import java.util.HashSet;

class A{
public boolean equals(Object obj){
return true;
}
}

class B{
public int hashCode(){
return 1;
}
}

class C{
public int hashCode(){
return 2;
}
public boolean equals(Object obj){
return true;
}
}

public class HashSetTest {
public static void main(String[] args) {
HashSet books
= new HashSet();
books.add(
new A());
books.add(
new A());
books.add(
new B());
books.add(
new B());
books.add(
new C());
books.add(
new C());
System.out.println(books);
}
}
 
 

attention problems: When an object is placed in the HashSet, if you need to override the object corresponding to the class equals () method, you should also override its hashCode () method. The rule is: If two objects through the equals () method comparison returns true, then the two objects hashCode value should be the same.

 

override hashCode () method of the basic rules:
1) in program is running, the same object multiple calls hashCode () method should return the same value.
2) When two objects through the equals () method returns true when comparing these two objects hashCode () method should return an equal values.
3) is used as an object equals () method is the standard Field, should be used to calculate the hashCode value.

 

If you add a variable to the HashSet object, subsequent changes in procedures of the variable object Field, it may lead to other elements in the same collection, This may lead to the HashSet contains two identical objects.

 
  
package cn.it.lsl; 

import java.util.HashSet;
import java.util.Iterator;

class R{
int count;
public R(int count){
this.count = count;
}
public String toString(){
return "R[count:" + count + "]";
}
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj != null && obj.getClass() == R.class){
R r
= (R)obj;
if(r.count == this.count){
return true;
}
}
return false;
}
public int hashCode(){
return this.count;
}
}
public class HashSetTest2 {
public static void main(String[] args) {
HashSet hs
= new HashSet();
hs.add(
new R(5));
hs.add(
new R(-3));
hs.add(
new R(9));
hs.add(
new R(-2));
System.out.println(hs);
Iterator it
= hs.iterator();
R first
= (R)it.next();
first.count
= -3;
System.out.println(hs);
hs.remove(
new R(-3));
System.out.println(hs);
System.out.println(
"hs是否包含count为-3的R对象?" + hs.contains(new R(-3)));
System.out.println(
"hs是否包含count为5的R对象?" + hs.contains(new R(5)));
}
}
 
 

when added to a HashSet variable object, you must be very careful. If you modify the HashSet object in the collection, it may lead to the object and other objects in the collection are equal, resulting HashSet unable to accurately access the object.

 

2) LinkedHashSet class
HashSet there is a sub-class LinkedHashSet, LinkedHashSet hashCode collection is based on the value of the element to determine the elements of the storage location, but it also maintains the order of elements using the linked list, which makes insertion sequence elements appear is saved.
That is, when traversing LinkedHashSet in the collection element, LinkedHashSet will be added according to the elements in order to access the elements of the collection.

 
  
package cn.it.lsl; 

import java.util.LinkedHashSet;

public class LinkedHashSetTest {
public static void main(String[] args) {
LinkedHashSet books
= new LinkedHashSet();
books.add(
"java");
books.add(
"Android");
System.out.println(books);
books.remove(
"java");
books.add(
"java");
System.out.println(books);
}
}
 
 

output LinkedHashSet elements of the collection, the order of the elements is always added in the same order.
although LinkedHashSet collection of records using a linked list elements are added sequentially, but still LinkedHashSet HashSet, so it still does not allow the collection element repeats.

 

3) TreeSet class
TreeSet is a SortedSet interface implementation class, you can collection elements in order to ensure the state.
TreeSet in several ways:
Object first (): returns the first element in the collection.
Object last (): returns the last element in the collection.
Object lower (Object e): returns the collection at the specified element before the element (ie the largest element less than the specified elements, parameter element does not require is a collection of elements TreeSet).
Object higher (Object e): returns the collection at the specified element after element (ie, greater than the smallest element of the specified element, parameter element does not require is a collection of elements TreeSet).
SortedSet subSet (formElement, toElement): return times Set subsets, ranging from formElement (included) to toElement (not included).
SortedSet headSet (toElement): Set to return this subset of elements from the less than toElement.
SortedSet tailSet (fromElement): Set to return this subset is greater than or equal to fromElement by the elemental composition.

 
  
package cn.it.lsl; 

import java.util.TreeSet;

public class TreeSetTree {
public static void main(String[] args) {
TreeSet nums
= new TreeSet();
nums.add(
5);
nums.add(
2);
nums.add(
10);
nums.add(
-9);
System.out.println(nums);
System.out.println(nums.first());
System.out.println(nums.last());
System.out.println(nums.headSet(
4)); //不包含4
System.out.println(nums.tailSet(5)); //包含5
System.out.println(nums.subSet(-3, 4));
}
}
 
 

4) EnumSet class
EnumSet is an enumeration class designed specifically for collection classes, EnumSet all elements must be specified enumeration type enum value.
EnumSet class does not expose any constructor to create instances of the class, the program should be adopted which provides static methods to create EnumSet object.
static EnumSet allOf (Class elementType): Create a class that contains all of the specified enumeration enumeration values ​​EnumSet collections.
static EnumSet complementOf (EnumSet s): Creates an element type with a specified type of elements EnumSet same EnumSet collection, the new collection contains original EnumSet EnumSet collection are not contained, the rest of this enumeration type enum values ​​(ie the new collections and the original EnumSet EnumSet collection elements add up to a collection class that enumerates all the enumeration values).
static EnumSet copyOf (Collection c): Use an ordinary collection to create EnumSet collections.
static EnumSet copyOf (EnumSet s): Creating an element with the specified EnumSet have the same type, the same set of elements EnumSet collections.
static EnumSet noneOf (Class elementType): Create an element type is specified enumeration type empty EnumSet.
static EnumSet of (E first, E. .. rest): Create an enum that contains one or more values ​​EnumSet collection, transmission into multiple enumeration values ​​must belong to the same enumeration class.
static EnumSet range (E from, E to): Create a enum value from from the range of values ​​to the To enumerate all enumeration values ​​EnumSet collections.

 
  
package cn.it.lsl; 

import java.util.EnumSet;

enum Season{
SPRING,SUMMER,FAIL,WINTER
}
public class EnumSetTest {
public static void main(String[] args) {
EnumSet es1
= EnumSet.allOf(Season.class);
System.out.println(es1);
EnumSet es2
= EnumSet.noneOf(Season.class);
System.out.println(es2);
es2.add(Season.WINTER);
es2.add(Season.SPRING);
System.out.println(es2);
EnumSet es3
= EnumSet.of(Season.SUMMER , Season.WINTER);
System.out.println(es3);
EnumSet es4
= EnumSet.range(Season.SUMMER, Season.WINTER);
System.out.println(es4);
EnumSet es5
= EnumSet.complementOf(es4);
System.out.println(es5);
}
}
 
 

copy another EnumSet all elements of the collection to create a new EnumSet collection, or copy another Collection of all the elements in the collection to create a new EnumSet collections. When copying all the elements in the collection Collection to create a new collection EnumSet require Collection all elements in the collection must be the same enum class enum value.

 
  
package cn.it.lsl; 

import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;

public class EnumSetTest2 {
public static void main(String[] args) {
Collection c
= new HashSet();
c.clear();
c.add(Season.FAIL);
c.add(Season.SPRING);
EnumSet enumSet
= EnumSet.copyOf(c);
System.out.println(enumSet);
// c.add("java");
// c.add("Android");
// enumSet = EnumSet.copyOf(c);
}
}
 
 

when trying to copy a Collection element of the collection to create EnumSet collections, you must ensure that all the elements of the collection Collection are the same enum class enum values .

 

Summary:

 

HashSet TreeSet performance is always better than a good (especially the most commonly used to add, query elements and other operations), as TreeSet requires additional red-black tree algorithm to maintain the collection The order of elements. Only when you need one to keep sorted Set only when you should use TreeSet, otherwise you should use HashSet.
for ordinary insert and delete operations, LinkedHashSet to be slightly slower than HashSet, which is caused by the maintenance overhead chain caused ; however, because of the linked list traversal LinkedHashSet will be faster.
EnumSet is all Set to achieve the best performance of the class, but it can only be saved with an enum class enum value as a collection element .

没有评论:

发表评论