Java Tutorial/Collections/HashSet — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:04, 1 июня 2010

Содержание

Adding Another Collection with the addAll() method: public boolean addAll(Collection c)

Each element in the collection passed in will be added to the set via the equivalent of calling the add() method on each element.

If the underlying set changes, true is returned.

If no elements are added, false is returned.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    elements = new String[] { "E", "F" };
    set.addAll(Arrays.asList(elements));
    System.out.println(set);
  }
}



[D, A, F, C, B, E]


Adding Single Elements: the add() method

To modify an element in a set, you should remove it, modify it, and then re-add it.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    set.add("Z");
    System.out.println(set);
  }
}



[Z, D, A, C, B, E]


An easy way to initialize a set without manually adding each element

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    System.out.println(set);
  }
}



[D, A, C, B, E]


Check if a particular element exists in HashSet

import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    System.out.println(hSet.contains(new Integer("3")));
  }
}





Checking for Existence: the contains() method reports if a specific element is within the set

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    System.out.println(set.contains("A"));
  }
}



true


Checking for no elements in the set: use the isEmpty() method instead

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    System.out.println(set.isEmpty());
  }
}



false


Convert array to Set

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Main {
  public static void main(String[] args) {
    Integer[] numbers = { 7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4 };
    List<Integer> list = Arrays.asList(numbers);
    Set<Integer> set = new HashSet<Integer>(list);
    for (Iterator iterator = set.iterator(); iterator.hasNext();) {
      Object o = iterator.next();
      System.out.print(o + ", ");
    }
  }
}





Converting elements in a set to Array: public Object[] toArray()

The first toArray() method will return an Object array containing all the elements in the collection.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    Object[] arrObj = set.toArray();
    for (int i = 0; i < arrObj.length; i++) {
      System.out.println(arrObj[i]);
    }
    System.out.println(set); 
  }
}



D
A
C
B
E
[D, A, C, B, E]


Copy all elements of HashSet to an Object Array

import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    Object[] objArray = hSet.toArray();
    for (Object obj : objArray)
      System.out.println(obj);
  }
}





Copying and Cloning Sets: public Object clone()

Calling the clone() method of a HashSet creates a shallow copy of that HashSet.

(the elements of the set aren"t duplicated. Both sets will refer to the same elements.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    Set set2 = ((Set) ((HashSet) set).clone());
    System.out.println(set2);
  }
}



[D, A, C, B, E]


Create unique lists of items?

import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String args[]) {
    String[] name1 = { "Amy", "Jose", "Jeremy", "Alice", "Patrick" };
    String[] name2 = { "Alan", "Amy", "Jeremy", "Helen", "Alexi" };
    String[] name3 = { "Adel", "Aaron", "Amy", "James", "Alice" };
    Set<String> letter = new HashSet<String>();
    for (int i = 0; i < name1.length; i++)
      letter.add(name1[i]);
    for (int j = 0; j < name2.length; j++)
      letter.add(name2[j]);
    for (int k = 0; k < name3.length; k++)
      letter.add(name3[k]);
    System.out.println(letter.size() + " letters must be sent to: " + letter);
  }
}



11 letters must be sent to: [Patrick, Amy, Jeremy, Adel, Alexi, Aaron, Jose, Alice, James, Helen, Alan]


Creating a HashSet

The HashSet class provides four constructors broken into two sets. The first three constructors create empty sets of varying sizes:



public HashSet()
public HashSet(int initialCapacity)
public HashSet(int initialCapacity, int loadFactor)



If the original collection had duplicates, only one of the duplicates will be in the final created set.


Fetching Elements: to work with all of the elements of the set

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    Iterator iter = set.iterator();
    while (iter.hasNext()) {
      System.out.println(iter.next());
    }
  }
}



D
A
C
B
E


Find maximum element of HashSet

import java.util.Collections;
import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Long> hashSet = new HashSet<Long>();
    hashSet.add(new Long("1111111111"));
    hashSet.add(new Long("2222222222"));
    hashSet.add(new Long("3333333333"));
    hashSet.add(new Long("4444444444"));
    hashSet.add(new Long("5555555555"));
    Object obj = Collections.max(hashSet);
    System.out.println(obj);
  }
}





Find Minimum element of HashSet

import java.util.Collections;
import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Long> hashSet = new HashSet<Long>();
    hashSet.add(new Long("9"));
    hashSet.add(new Long("4"));
    hashSet.add(new Long("2"));
    hashSet.add(new Long("2"));
    hashSet.add(new Long("3"));
    Object obj = Collections.min(hashSet);
    System.out.println("Minimum Element of HashSet is : " + obj);
  }
}





Get Enumeration over HashSet

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<String> hashSet = new HashSet<String>();
    hashSet.add("A");
    hashSet.add("B");
    hashSet.add("D");
    hashSet.add("E");
    hashSet.add("F");
    Enumeration e = Collections.enumeration(hashSet);
    while (e.hasMoreElements())
      System.out.println(e.nextElement());
  }
}





Get Size of HashSet

import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    System.out.println("Size of HashSet : " + hSet.size());
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    System.out.println(hSet.size());
    hSet.remove(new Integer("1"));
    System.out.println(hSet.size());
  }
}
/*
Size of HashSet : 0
3
2
*/





Get Synchronized Set from HashSet

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Main {
  public static void main(String[] args) {
    HashSet hashSet = new HashSet();
    Set set = Collections.synchronizedSet(hashSet);
  }
}





HashSet implements the empty Serializable interface

If, and only if, all of the elements of a HashSet are Serializable, HashSet can be saved to an ObjectOutputStream and later read it in to an ObjectInputStream.



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) throws Exception{
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    
    FileOutputStream fos = new FileOutputStream("set.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(set);
    oos.close();
    
    FileInputStream fis = new FileInputStream("set.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Set anotherSet = (Set) ois.readObject();
    ois.close();
    System.out.println(anotherSet);
  }
}



[D, A, C, B, E]


Integer value set

import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    System.out.println("HashSet contains.." + hSet);
  }
}
//HashSet contains..[1, 2, 3]





Iterate through elements of HashSet

import java.util.HashSet;
import java.util.Iterator;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    Iterator itr = hSet.iterator();
    while (itr.hasNext())
      System.out.println(itr.next());
  }
}





Listing the Elements of a Collection(iterate over the elements of set or list)

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Main {
  public static void main(String[] argv) throws Exception {
    Set collection = new HashSet();
    // For a set or list
    for (Iterator it = collection.iterator(); it.hasNext();) {
      Object element = it.next();
    }
  }
}





Making a Collection Read-Only

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Main {
  public static void main(String[] argv) throws Exception {
    List stuff = Arrays.asList(new String[] { "a", "b" });
    List list = new ArrayList(stuff);
    list = Collections.unmodifiableList(list);
    try {
      list.set(0, "new value");
    } catch (UnsupportedOperationException e) {
      
    }
    Set set = new HashSet(stuff);
    set = Collections.unmodifiableSet(set);
    Map map = new HashMap();
    map = Collections.unmodifiableMap(map);
  }
}





public Object[] toArray(Object[] a)

When all elements of a collection are of the same type, it is easier for you to work with an array of that specific type.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    String[] strObj = new String[set.size()];
    strObj = (String[]) set.toArray(strObj);
    for (int i = 0; i < strObj.length; i++) {
      System.out.println(strObj[i]);
    }
    System.out.println(set);
  }
}



D
A
C
B
E
[D, A, C, B, E]


Remove all elements from HashSet

import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    System.out.println(hSet);
    hSet.clear();
    System.out.println(hSet);
    System.out.println(hSet.isEmpty());
  }
}
/*
[1, 2, 3]
[]
true
*/





Remove specified element from HashSet

import java.util.HashSet;
public class Main {
  public static void main(String[] args) {
    HashSet<Integer> hSet = new HashSet<Integer>();
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
    System.out.println(hSet);
    boolean blnRemoved = hSet.remove(new Integer("2"));
    System.out.println(blnRemoved);
    System.out.println(hSet);
  }
}
/*
[1, 2, 3]
true
[1, 3]
*/





Removing All Elements: public void clear()

You can still get an UnsupportedOperationException thrown when working with a read-only set.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    elements = new String[] { "E", "F" };
    set.addAll(Arrays.asList(elements));
    System.out.println(set);
    set.clear();
    System.out.println(set);
  }
}



[D, A, F, C, B, E]
 []


Removing Single Elements: public boolean remove(Object element)

Determining via the equals() method of the element.

If the element is found, the element is removed and true is returned.

If not found, false is returned.

If removal is not supported, you"ll get an UnsupportedOperationException thrown.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    set.remove("A");
    System.out.println(set);
  }
}



[D, C, B, E]


Set and HashSet

  1. A Set represents a mathematical set.
  2. It is a Collection that, unlike List, does not allow duplicates.
  3. There must not be two elements of a Set, say e1 and e2, such that e1.equals(e2).
  4. The add method of Set returns false if you try to add a duplicate element.



import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    Set set = new HashSet();
    set.add("Hello");
    if (set.add("Hello")) {
      System.out.println("addition successful");
    } else {
      System.out.println("addition failed");
    }
  }
}



addition failed
  1. HashSet allows at most one null element.
  2. HashSet is faster than other implementations of Set, TreeSet and LinkedHashSet.


the containsAll() method checks if a set contains another whole collection

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    elements = new String[] { "A", "B", "C" };
    Set set2 = new HashSet(Arrays.asList(elements));
    System.out.println(set.containsAll(set2));
  }
}



true


The HashSet class defines equality through its equals() method: public boolean equals(Object o)

A HashSet is equal to another object if the other object implements the Set interface, has the same size(), and contains all the same elements.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    elements = new String[] { "A", "B", "C", "D" };
    Set set2 = new HashSet(Arrays.asList(elements));
    System.out.println(set.equals(set2));
  }
}



false


To find out how many elements are in a set, use the size() method

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));
    System.out.println(set.size());
  }
}



5