它的类型独特?

时间:2014-12-15 20:11:58

标签: java class types unique

每个电话号码的类型必须是唯一的。它们必须存储为两个字段:电话类型(工作,家庭,小区)和号码。 我如何在java中编写类似的类? 以下是不是真的?

public class PhoneNumber {

   private int number;
   private String type;

public PhoneNumber(int number1,String type1){

    setNumber(number1);
    setType(type1);
}

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

public class PhoneNumber {

    private int number;
    private String type;

    public static Map<Integer, PhoneNumber> knownNumbers = new HashMap<Integer, PhoneNumber>();

    public PhoneNumber(int number1,String type1) throws AlreadyExistsNumberException{
        validate(number1);
        this.number = number1;
        this.type = type1;

        knownNumbers.put(number, this);
    }



    private void validate(int number1) {
        if(knownNumbers.get(number1) != null){
            throw new AlreadyExistsNumberException("The number "+number1+" already exists");
        }
    }
}

然后,例如:

try{
    PhoneNumber number = new PhoneNumber(66666666, "Mobile");
}catch(AlreadyExistsNumberException e){
    //Deal with the problem
}

当然有几种方法可以解决这个问题,你也可以使用静态方法来检查它,使用布尔方法来查看它是否已经存在等等......

修改

另一种选择:

public class PhoneNumber {

    private int number;
    private String type;

    public static Map<Integer, PhoneNumber> knownNumbers = new HashMap<Integer, PhoneNumber>();

    public PhoneNumber(int number1,String type1){
        this.number = number1;
        this.type = type1;

        knownNumbers.put(number, this);
    }

    private static boolean validate(int number1) {
        return (knownNumbers.get(number1) == null);
    }
}

它的用法:

int number = 66666666;
String type = "Cell";
if(validate(number))
    PhoneNumber phoneNumber = new PhoneNumber(number, type);

答案 1 :(得分:1)

您不应将ints用于您的电话号码。首先,电话号码是10位数(全部为正数),因此它们很容易超过int的容量。另一方面,电话号码不是整数...你永远不会添加或减少或乘以电话号码。

这是它应该是什么样子:

public enum PhoneType { ... // fill in the possible phone types
}

public static final EnumMap<PhoneType, Set<String>> phoneNumbers = new EnumMap<PhoneType, Set<String>>(); 

您可能希望围绕这些DT构建一些控制来获取/设置电话号码,但这应该可以帮助您开始