hashcode, equals and compareTo

This commit is contained in:
Florian Steurer 2015-10-24 18:53:11 +02:00
parent b0153be1cd
commit 3d38ea2e08

View File

@ -2,17 +2,19 @@ package de.dhbwstuttgart.typinference.unify.model;
import java.util.Arrays;
import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException;
/**
*
* @author DH10STF
*
* SPEEDUP
* TODO SPEEDUP
* - Caching of the results
* - Global map from int to mtype und mtype[] array mit int[] austauschen und wenn nötig nachschlagen
* - Vorteil: Jeder Typ wäre globally unique -> Memory effizient
* - Nachteil: Nachschlagen kostet zeit, Dictionary muss gemanaged werden
* - TypeArgs in HashCode berechnung stärker / weniger einbeziehen
*/
public class MType {
public class MType implements Comparable<MType>{
/**
* First three bits indicate the meta type:
* 000b = 0 = Simpletype
@ -23,11 +25,12 @@ public class MType {
*
* Advantages of using a unique identifier for mapping:
* - Fast checks (Equality and Membership)
* - Perfect Hashing
* - Easy Hashing
* - Memory efficient
*/
private int identifier = 0;
private int[] typeArgs = null;
private MType[] typeArgs = null;
/**
* Used to mask the first three bits of an integer.
@ -35,13 +38,10 @@ public class MType {
*/
private final int mask = -53870912;
public MType(int identifier, int...typeArgs) {
public MType(int identifier, MType... typeArgs) {
this.identifier = identifier;
if(typeArgs.length != 0) {
this.typeArgs = Arrays.copyOf(typeArgs, typeArgs.length);
Arrays.sort(typeArgs);
}
this.typeArgs = Arrays.copyOf(typeArgs, typeArgs.length);
Arrays.sort(typeArgs);
}
public boolean isSimpleType() {
@ -68,17 +68,48 @@ public class MType {
return identifier;
}
public MType[] getTypeArgs() {
return typeArgs;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof MType))
return false;
if(obj.hashCode() != hashCode())
return false;
throw new NotImplementedException();
MType other = (MType) obj;
if(other.getIdentifier() != identifier)
return false;
MType[] otherTypeArgs = other.getTypeArgs();
if(otherTypeArgs.length != typeArgs.length)
return false;
for(int i = 0; i < typeArgs.length; i++)
if(!typeArgs[i].equals(otherTypeArgs[i]))
return false;
return true;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
return identifier + 31 * typeArgs.length;
}
@Override
public int compareTo(MType o) {
// Comparison is insensitive to type arguments.
if(o.getIdentifier() > identifier)
return -1;
if(o.getIdentifier() < identifier)
return 1;
return 0;
}
}