欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java中的类集之set,javaset

来源: javaer 分享于  点击 404 次 点评:224

Java中的类集之set,javaset


Set可以理解为集合,它与List和Queue最大的不同点在于,它里面存放的元素不能有重复。它有两个常用的实现类:HashSet和TreeSet。

集合主要用来存放数据,因此只提供了添加和删除数据的方法:add(obj),remove(Obj),这里的obj表示集合中的元素。如果添加或者删除成功时返回true否则返回false。因为集合中不能有重复的元素,所以有必要在添加元素时判断是否添加成功。添加进去的元素存放在哪个位置由集合来确定,因此不能确定被添加元素的具体位置。鉴于这个原因set不支持像链表一样按照索引添加/删除元素。

另外,clear()方法用来清空集合中所有的元素,清空后会变成空集合。与List和Queue接口相比,Set接口提供的方法不多,不过我们还是使用文字结合代码的方式来演示如何使用它们。下面是具体的代码,请参考:

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

public class setEx {
 public static void main(String args[]){
  // init set
  Set set = new HashSet<>();
  for (int i = 0; i < 10; ++i) {
// set.add(new Integer(i+1));
set.add((i + 1));
  }

  // show size of set ,and content of set
  System.out.println("size of set: " + set.size());
  for (Integer i : set)
System.out.print(i + " ");

  System.out.println("\nset: " + set);

  // delete the content of set,this is based on content of set
  if(set.remove(9)) {
System.out.println("after removing the content 9. set: " + set);
  } else {
System.out.println("removing the content 9 failed.");
  }

  // delete the same content of set,it is failed to remove
  if(set.remove(9)) {
System.out.println("after removing the content 9. set: " + set);
  } else {
System.out.println("removing the content 9 failed.");
  }

  // add the same content of set,it is failed to add 
  if(set.add(9)) {
System.out.println("after adding the content 9. set: " + set);
  } else {
System.out.println("adding the content 9 failed.");
  }

  // add the content of set,this is based on content of set
  if(set.add(9)) {
System.out.println("after adding the content 9. set: " + set);
  } else {
System.out.println("adding the content 9 failed.");
  }

  // change set to array
  Integer[] array = set.toArray(new Integer[] {});
  System.out.println("change set to array: " + Arrays.toString(array));

  // add the content of set,this is based on content of set
  set.clear();
  System.out.println("after clearing the set: " + set);
 }
}

下面是程序的运行结果,请参考:

size of set: 10
1 2 3 4 5 6 7 8 9 10 
set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after removing the content 9. set: [1, 2, 3, 4, 5, 6, 7, 8, 10]
removing the content 9 failed.
after adding the content 9. set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
adding the content 9 failed.
change set to array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after clearing the set: []

各位看官,关于Java中类集之Set的例子咱们就介绍到这里

相关栏目:

用户点评