SORU
13 Mart 2011, Pazar


Java Numaralama eşleştirme için bir tamsayı değeri dönüştürmek

Böyle bir sıralama yaptım:

public enum PcapLinkType {
  DLT_NULL(0)
  DLT_EN10MB(1)
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  DLT_UNKNOWN(-1);
    private final int value;   

    PcapLinkType(int value) {
        this.value= value;
    }
}

Şimdi dış giriş int olsun ve eşleştirme giriş - eğer bir değeri varsa bir istisna atma tamam, ama tercihen DLT_UNKNOWN Bu durumda olması gerekirdi.

int val = in.readInt();
PcapLinkType type = ???; /*convert val to a PcapLinkType */

CEVAP
13 Mart 2011, Pazar


Bunu el ile yapmak için, çeteleler için Tamsayılar haritalar sınıf statik bir harita gibi bir ekleyerek gerekir

private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.value, type);
    }
}

public static PcapLinkType fromInt(int i) {
    PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
    if (type == null) 
        return PcapLinkType.DLT_UNKNOWN;
    return type;
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ChasesAndCrashes

    ChasesAndCra

    31 Temmuz 2009
  • Dom Esposito

    Dom Esposito

    26 Mayıs 2011
  • Kassem G

    Kassem G

    25 EKİM 2006