【java】collection-->set

原文地址:

http://examples.javacodegeeks.com/core-java/util/set/java-set-example/


In this example we will demonstrate the use of the interface Set, which is part of the Java Collections Framework. It extends the interface Collection so that all elements contained have no dublicates and only one null element may appear.

There are several classes implementing the interface, such as AbstractSetEnumSetHashSetLinkedHashSetTreeSetand ConcurrentSkipListSet. The classes HashSet and TreeSet are the most commonly used.

HashSet implements the interface using a hash table. It offers high performance for the basic methods such as add, remove, contains and size, however the ordering of the elements cannot be tracked and possibly it could change at anytime during execution.

TreeSet uses a TreeMap to store the elements, which keeps them sorted by their natural order or by the comparator that we prefer to use.

1. How to create a Set:

HashSet()
构造一个新的空 set,其底层 HashMap 实例的默认初始容量是 16,加载因子是 0.75。
HashSet(Collection<? extends E> c)
构造一个包含指定 collection 中的元素的新 set。
HashSet(int initialCapacity)
构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和默认的加载因子(0.75)。
HashSet(int initialCapacity, float loadFactor)
构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和指定的加载因子

2. Common Methods:

  • add(Object): Adds a new element, if it does not exist already.
  • addAll(Collection): Adds all the elements of the given collection, if the do not exist already. If the given collection is also a set, then the execution of the method results in the union of the two sets.
  • contains(Object): Returns true if the elements given exists in the set.
  • containsAll(Collection): Returns true if all the elements in the given collection exist in the set. In case the given collection is a set, the method return true if it is a subset of this set.
  • equals(Object): Returns true if the given object that is compared with this set is also a set, both of them contain the same number of elements and every element of the given set is contained in this set.
  • size(): Returns the number of the elements in the set.
  • remove(Object): Removes the specified elements from the set.
  • removeAll(Collection): Removes from the set all the elements that the collection contains.
  • clear(): Removes all the elements from the set, resulting in an empty set.
  • isEmpty(): Returns true if the set has no elements.
  • hashCode(): Returns the hash code value of this set. The hash code of a set is the sum of the hash codes of the elements contained in the set.
  • toArray(): Return an array containing all the elements of this set.

3. Examples of using Set in Java:


package lvzheming;

import java.util.*;

public class ExamplesofusingSetinJava{

public static void main(String args[]) {

 // We create a new, empty set
 Set mySet1 = new HashSet();
 // We add a few elements
 mySet1.add("A");
 mySet1.add("B");
 mySet1.add("C");
 mySet1.add("D");
 // Print the elements of the Set
 System.out.println("mySet1: " + mySet1);

 // Create a list and add some elements
 List list = new ArrayList();
 list.add("A");
 list.add("B");
 list.add("C");
 list.add("D");
 list.add("E");
 list.add("F");
 // Now create the set using the appropriate constructor
 Set mySet2 = new HashSet(list);
 // Print the elements of the list an the the set
 System.out.println("list: " + list);
 System.out.println("mySet2: " + mySet2);

 // Compare the two sets
 System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

 // Now we will remove one element from mySet2 and compare again
 mySet2.remove("A");
 System.out.println("mySet2: " + mySet2);
 System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));
 mySet2.add("A");

 // Lets check if our sets contain all the elements of the list
 System.out.println("MySet1 contains all the elements: " + mySet1.containsAll(list));
 System.out.println("MySet2 contains all the elements: " + mySet2.containsAll(list));

 // Use of Iterator in Set 
 //迭代器能够自动识别集合元素的类型,只要使用next就可以自动输出所有集合的内容
 Iterator iterator = mySet1.iterator();
 //Returns true if the iteration has more elements. 
 while (iterator.hasNext()) {
	 //Returns the next element in the iteration.
     System.out.println("Iterator loop: " + iterator.next());
 }

 // Use of for-each in Set
 for (Object str : mySet1) {
     System.out.println("for-each loop: " + str);
 }

 // Clearing all the elements
 mySet1.clear();
 System.out.println("mySet1 is Empty: " + mySet1.isEmpty());

 // Checking the number of elements
 System.out.println("mySet1 has: " + mySet1.size() + " Elements");
 System.out.println("mySet2 has: " + mySet2.size() + " Elements");

 // Creating an Array with the contents of the set
 String[] array = (String[]) mySet2.toArray(new String[mySet2.size()]);
 System.out.println("The array:" + Arrays.toString(array));
}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值