Implement ArraySet

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Implement ArraySet

This is a Java example program.

[edit] Java Source Code

  • Package: example.array
  • File: ArraySet.java
  1. package example.array;
  2.  
  3. import java.io.Serializable;
  4. import java.util.AbstractSet;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.Collection;
  8. import java.util.Iterator;
  9. import java.util.Set;
  10.  
  11. public class ArraySet extends AbstractSet implements Cloneable, Serializable {
  12.  
  13.     private ArrayList list;
  14.  
  15.     public ArraySet() {
  16. 	list = new ArrayList();
  17.     }
  18.  
  19.     public ArraySet(Collection col) {
  20. 	list = new ArrayList();
  21.  
  22. 	// No need to check for dups if col is a set
  23. 	Iterator itor = col.iterator();
  24. 	if (col instanceof Set) {
  25. 	    while (itor.hasNext()) {
  26. 		list.add(itor.next());
  27. 	    }
  28. 	} else {
  29. 	    while (itor.hasNext()) {
  30. 		add(itor.next());
  31. 	    }
  32. 	}
  33.     }
  34.  
  35.     public Iterator iterator() {
  36. 	return list.iterator();
  37.     }
  38.  
  39.     public int size() {
  40. 	return list.size();
  41.     }
  42.  
  43.     public boolean add(Object element) {
  44. 	boolean modified;
  45. 	if (modified = !list.contains(element)) {
  46. 	    list.add(element);
  47. 	}
  48. 	return modified;
  49.     }
  50.  
  51.     public boolean remove(Object element) {
  52. 	return list.remove(element);
  53.     }
  54.  
  55.     public boolean isEmpty() {
  56. 	return list.isEmpty();
  57.     }
  58.  
  59.     public boolean contains(Object element) {
  60. 	return list.contains(element);
  61.     }
  62.  
  63.     public void clear() {
  64. 	list.clear();
  65.     }
  66.  
  67.     public Object clone() {
  68. 	try {
  69. 	    ArraySet newSet = (ArraySet) super.clone();
  70. 	    newSet.list = (ArrayList) list.clone();
  71. 	    return newSet;
  72. 	} catch (CloneNotSupportedException e) {
  73. 	    throw new InternalError();
  74. 	}
  75.     }
  76.  
  77.     public static void main(String args[]) {
  78. 	String elements[] = { "Java", "Source", "and", "Support", "." };
  79. 	Set set = new ArraySet(Arrays.asList(elements));
  80. 	Iterator iter = set.iterator();
  81. 	while (iter.hasNext()) {
  82. 	    System.out.println(iter.next());
  83. 	}
  84.     }
  85. }

[edit] What Result You Can Get

Run the program, you will get:

Java
Source
and
Support
.

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools