将唯一元素添加到用户定义类的List / HashSet(即List <operand>)</operand>

时间:2012-01-21 05:57:50

标签: c#

将唯一元素添加到用户定义类列表(即列表)

public class Operand: IEnumerable, IEnumerator
{ 
public String opr;
public String state;
}

我想制作它并实现所有必要的例程来应用List。 (注意:类操作数:IEnumerable,IEnumerator)

但是当我试图添加元素即操作数的对象时 operand tem1 = new Operand(“eax”,“undef”);

operand tem2=new Operand("ebx","undef");

operand tem3=new Operand("ecx","undef");

operand tem4=new Operand("eax","undef");
operand tem5=new Operand("eax","undef");

然后我想在List OR HashSet中添加这5个temp [1-5]元素。 如果有重复元素,则将该元素的状态更新为Def ieDefine

我该怎么做... 请帮帮我..

2 个答案:

答案 0 :(得分:2)

Operand班级中覆盖GetHashCodeMethodEquals方法。确保为唯一的Operand实例返回唯一的HashCode,并确保两个操作数相同,即它们的属性值相同,在equals方法中返回true,否则返回false

public override bool Equals(object obj)
        {
            if(obj is Operand)
            {
                Operand op = obj as Operand;
                if (this.opr == op.opr && this.state == op.state)
                    return true;
            }
            return false;
        }

  public override int GetHashCode()
    {
        int hash = 13;
        hash = (hash * 7) + opr.GetHashCode();
        hash = (hash * 7) + state.GetHashCode();
        return hash;
    }

实施这些方法后,您可以使用List方法检查Hashset Contains中的重复项。如果您发现重复而不是插入新记录,则更新现有记录。

答案 1 :(得分:-2)

将此代码放在operand.java文件中:

public class Operand
{ 
public String opr;
public String state;
}

现在在其他bean.java文件中编写此代码

public class bean {
    List<operand> mylist = new ArrayList<operand>();
    String[] opr = new String[]{"eax","ecx","eax","eax"};
    String[] state = new String[]{"def","def","def","def"};
    operand[] o = new operand[4];
    public bean() {
        for (int i = 0; i <=3; i++) {
            o[i] = new operand();
            o[i].setCity(opr[i]);
            o[i].setName(state[i]);
            mylist.add(o[i]);
        }
    }
}

我认为这对你有用,试一试。