using System;
using System.Collections.Generic;
namespace ObjTec.Collections
{
class Set<T> : List<T>
{
public new T this[int index]
{
get { return base[index];}
set
{
if (this.Contains(value))
throw new ArgumentException("Duplicate object.");
base[index] = value;
}
}
public new void Add(T item)
{
if (this.Contains(item))
throw new ArgumentException("Duplicate object.");
base.Add(item);
}
public new void Insert(int index, T item)
{
if ( this.Contains(item)) this.Remove(item);
this.Insert(index, item);
}
public new bool Remove(T item )
{
if (!this.Contains(item)) return false;
return this.Remove(item);
}
public new bool Contains(T item)
{
if (item == null)
throw new ArgumentException("Set cannot contain null items");
return base.Contains(item);
}
public static Set<T> operator & (Set<T> lhs, Set<T> rhs)
{
return lhs.Union(rhs);
}
public Set<T> Union(Set<T> aSet)
{
Set<T> unionSet = new Set<T>();
Set<T> sourceSet = null;
Set<T> mergeSet = null;
sourceSet = aSet.Count > this.Count ? aSet : this;
mergeSet = mergeSet == aSet ? this : aSet;
foreach(T item in sourceSet)
unionSet.Add(item);
foreach(T item in mergeSet)
if( !unionSet.Contains(item))
unionSet.Add(item);
return unionSet;
}
public static Set<T> operator |(Set<T> lhs, Set<T> rhs)
{
return lhs.Intersect(rhs);
}
public Set<T> Intersect(Set<T> aSet)
{
Set<T> commonSet = new Set<T>();
Set<T> sourceSet = null;
Set<T> mergeSet = null;
sourceSet = aSet.Count > this.Count ? aSet : this;
mergeSet = mergeSet == aSet ? this : aSet;
foreach(T item in mergeSet)
if (sourceSet.Contains(item)) commonSet.Add(item);
return commonSet;
}
public static Set<T> operator ^(Set<T> lhs, Set<T> rhs)
{
return lhs.Difference(rhs);
}
public Set<T> Difference(Set<T> aSet )
{
Set<T> result = new Set<T> ();
foreach(T item in aSet)
if ( !this.Contains(item)) result.Add(item);
foreach(T item in this)
if ( !aSet.Contains(item)) result.Add(item);
return result;
}
public static bool operator ==(Set<T> lhs , Set<T> rhs)
{
if (System.Object.ReferenceEquals(lhs,rhs)) return true;
if ( ( (object)lhs == null) || ( (object) rhs == null) )
return false;
return lhs.Equals(rhs);
}
public static bool operator != (Set<T> lhs, Set<T> rhs)
{
return ! (lhs == rhs);
}
public override bool Equals(object obj )
{
if ( obj == null ) return false;
Set<T> test = this as Set<T>;
if ( test == null ) return false;
if ( this.Count != test.Count) return false;
if ( !this.IsSubsetOf(test)) return false;
if ( !test.IsSubsetOf(this)) return false;
return true;
}
public bool IsSubsetOf(Set<T> aSet)
{
foreach(T item in this)
if ( !aSet.Contains(item) ) return false;
return true;
}
public bool IsSupersetOf(Set<T> aSet)
{
foreach( T item in aSet)
if ( !this.Contains(item) ) return false;
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}