aboutsummaryrefslogtreecommitdiffstats
path: root/Framework/hu.bme.mit.inf.dslreasoner.logic.model/src/hu/bme/mit/inf/dslreasoner/util/SetWithCustomEquivalence.xtend
blob: ae2cfb04894f7e7e2ee1f44f0a332d0070bce5c3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package hu.bme.mit.inf.dslreasoner.util

import org.eclipse.xtext.xbase.lib.Functions.Function1
import java.util.HashMap
import java.util.Set
import java.util.Collection
import java.util.HashSet

class SetWithCustomEquivalence<Type,Representation> implements Set<Type>{
	val Function1<Type,Representation> representer;
	val HashMap<Representation,Type> map
	
	public new(Function1<Type,Representation> representer) {
		this.representer = representer
		this.map = new HashMap<Representation,Type>
	}
	public new(Function1<Type,Representation> representer, Collection<? extends Type> initialElements) {
		this.representer = representer
		this.map = new HashMap
		initialElements.forEach[add]
	}
	
	override add(Type arg0) {
		val representation = representer.apply(arg0)
		if(!map.containsKey(representation)) {
			map.put(representation,arg0);
			return true
		} else return false
	}
	
	override addAll(Collection<? extends Type> arg0) {
		val originalSize = this.size
		arg0.forEach[add(it)]
		return (this.size != originalSize)
	}
	
	override clear() {
		map.clear
	}
	
	override contains(Object arg0) {
		try {
			val rep = this.representer.apply(arg0 as Type)
			return map.containsKey(rep)
		} catch (ClassCastException e) {
			return false
		}
	}
	
	override containsAll(Collection<?> arg0) {
		arg0.forall[it.contains]
	}
	
	override isEmpty() {
		return map.isEmpty
	}
	
	override iterator() {
		return map.values.iterator
	}
	
	override remove(Object arg0) {
		try {
			val rep = this.representer.apply(arg0 as Type)
			return map.remove(rep) != null
		} catch (ClassCastException e) {
			return false
		}
	}
	
	override removeAll(Collection<?> arg0) {
		val originalSize = this.size
		arg0.forEach[remove(it)]
		return (this.size != originalSize)
	}
	
	override retainAll(Collection<?> arg0) {
		val Set<Representation> representationsOfArg0 = new HashSet
		for(element: arg0) {
			try {
				representationsOfArg0 += this.representer.apply(element as Type)
			} catch(ClassCastException e) {}
		}
		val originalSize = this.size
		for(r:this.map.keySet) {
			if(!representationsOfArg0.contains(r))
				this.map.remove(r)
		}
		return (this.size != originalSize)
	}
	
	override size() {
		return this.map.size
	}
	
	override toArray() {
		map.values.toArray
	}
	
	override <T> toArray(T[] arg0) {
		map.values.toArray(arg0)
	}
}