public static void main(String[] args) { EnumMap<AlarmPoints, Command> em = new EnumMap<AlarmPoints, Command>(AlarmPoints.class); em.put( KITCHEN, new Command() { public void action() { print("Kitchen fire!"); } }); em.put( BATHROOM, new Command() { public void action() { print("Bathroom alert!"); } }); for (Map.Entry<AlarmPoints, Command> e : em.entrySet()) { printnb(e.getKey() + ": "); e.getValue().action(); } try { // If there's no value for a particular key: em.get(UTILITY).action(); } catch (Exception e) { print(e); } }
private JRadioButton getShapeButton( JRadioButton button, int x, int y, int w, int h, String tip, Shp shp, Obj obj) { button.setBounds(new Rectangle(x, y, w, h)); button.setBorder(BorderFactory.createLoweredBevelBorder()); button.setToolTipText(Messages.getString(tip)); button.addActionListener(alShape); shapeButtons.add(button); shapes.put(shp, button); objects.put(shp, obj); return button; }
public static void main(String[] args) { // 创建EnumMap对象,该EnumMap的所有key都是Season枚举类的枚举值 EnumMap enumMap = new EnumMap(Season.class); enumMap.put(Season.SUMMER, "夏日炎炎"); enumMap.put(Season.SPRING, "春暖花开"); System.out.println(enumMap); }
// [JACKSON-212] public void testToStringEnumWithEnumMap() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); EnumMap<LowerCaseEnum, String> enums = new EnumMap<LowerCaseEnum, String>(LowerCaseEnum.class); enums.put(LowerCaseEnum.C, "value"); assertEquals("{\"c\":\"value\"}", m.writeValueAsString(enums)); }
// [databind#601] public void testEnumsWithJsonValueInMap() throws Exception { EnumMap<EnumWithJsonValue, String> input = new EnumMap<EnumWithJsonValue, String>(EnumWithJsonValue.class); input.put(EnumWithJsonValue.B, "x"); assertEquals( "{\"" + EnumWithJsonValue.B.toString() + "\":\"x\"}", mapper.writeValueAsString(input)); }
public NetworkMockup() { this.initialFactTemplate = defTemplate("initial-fact", ""); defFacts("initial-fact", "", Arrays.asList(new TemplateContainer<>(initialFactTemplate))); { final Template dummyFact = this.defTemplate("dummy-fact", "used as default value for FACT-ADDRESS"); @SuppressWarnings("unchecked") final FactIdentifier dummyFactIdentifier = new org.jamocha.function.fwa.Assert<>( this, new TemplateContainer[] {new TemplateContainer<>(dummyFact)}) .evaluate(); for (final SlotType type : EnumSet.allOf(SlotType.class)) { switch (type) { case BOOLEAN: defaultValues.put(type, Boolean.FALSE); break; case DATETIME: defaultValues.put(type, ZonedDateTime.now()); break; case DOUBLE: defaultValues.put(type, Double.valueOf(0.0)); break; case LONG: defaultValues.put(type, Long.valueOf(0)); break; case NIL: defaultValues.put(type, null); break; case STRING: defaultValues.put(type, ""); break; case SYMBOL: defaultValues.put(type, this.getScope().getOrCreateSymbol("nil")); break; case FACTADDRESS: defaultValues.put(type, dummyFactIdentifier); break; case BOOLEANS: case DATETIMES: case DOUBLES: case FACTADDRESSES: case LONGS: case NILS: case STRINGS: case SYMBOLS: defaultValues.put(type, Array.newInstance(type.getJavaClass(), 0)); break; } } } }
public synchronized void decreaseStock(Book book, int quantity, int jobSeqNum) throws InterruptedException { while (!inventory.containsKey(book) || inventory.get(book).intValue() < quantity) { wait(); } inventory.put(book, inventory.get(book) - quantity); printWork(false, jobSeqNum, book, inventory.get(book) + quantity, inventory.get(book)); }
private Node( AbstractAction prevAct, ActionState state, Round prevRound, List<AbstractAction> path, PathToFlop pathToFlop) { if (pathToFlop != null) { PATH = pathToFlop; } else { if (prevAct != null) { path.add(prevAct); } PATH = PathToFlop.matching(path); } // nextIntent INDEX = nextIndex++; ID = nextId(PATH, state.round()); INTENT = nextIntent(prevRound); CAN_RAISE = state.canRaise(); CAN_CHECK = state.canCheck(); STATUS = state.headsUpStatus(); ROUND = state.round(); STAKES = state.stakes().smallBlinds(); DEALER_COMMIT = state.seat(1).commitment().smallBlinds(); DEALEE_COMMIT = state.seat(0).commitment().smallBlinds(); DEALER_NEXT = state.dealerIsNext(); STATE = state; KIDS = new EnumMap<>(AbstractAction.class); for (Map.Entry<AbstractAction, ActionState> act : state.actions(false).entrySet()) // state.viableActions().entrySet()) { List<AbstractAction> nextPath = (PATH == null) ? new ArrayList<>(path) : null; // if (! act.getValue().atEndOfHand()) { KIDS.put(act.getKey(), new Node(act.getKey(), act.getValue(), ROUND, nextPath, PATH)); // } } // intents F_INTENT = intent(AbstractAction.QUIT_FOLD); C_INTENT = intent(AbstractAction.CHECK_CALL); R_INTENT = intent(AbstractAction.BET_RAISE); KID_NODES = new Node[] { KIDS.get(AbstractAction.QUIT_FOLD), KIDS.get(AbstractAction.CHECK_CALL), KIDS.get(AbstractAction.BET_RAISE) }; }
private EnumMap<Location, Component> makeLookupMap(List<Component> components) { EnumMap<Location, Component> map = new EnumMap<BorderLayout.Location, Component>(Location.class); List<Component> unassignedComponents = new ArrayList<Component>(); for (Component component : components) { if (component.getLayoutData() instanceof Location) { map.put((Location) component.getLayoutData(), component); } else { unassignedComponents.add(component); } } // Try to assign components to available locations for (Component component : unassignedComponents) { for (Location location : AUTO_ASSIGN_ORDER) { if (!map.containsKey(location)) { map.put(location, component); break; } } } return map; }
@Override public EnumMap<?, ?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // Ok: must point to START_OBJECT if (jp.getCurrentToken() != JsonToken.START_OBJECT) { return _deserializeFromEmpty(jp, ctxt); } EnumMap result = constructMap(); final JsonDeserializer<Object> valueDes = _valueDeserializer; final TypeDeserializer typeDeser = _valueTypeDeserializer; while ((jp.nextToken()) == JsonToken.FIELD_NAME) { String keyName = jp.getCurrentName(); // just for error message // but we need to let key deserializer handle it separately, nonetheless Enum<?> key = (Enum<?>) _keyDeserializer.deserializeKey(keyName, ctxt); if (key == null) { if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) { throw ctxt.weirdStringException( keyName, _enumClass, "value not one of declared Enum instance names for " + _mapType.getKeyType()); } /* 24-Mar-2012, tatu: Null won't work as a key anyway, so let's * just skip the entry then. But we must skip the value as well, if so. */ jp.nextToken(); jp.skipChildren(); continue; } // And then the value... JsonToken t = jp.nextToken(); /* note: MUST check for nulls separately: deserializers will * not handle them (and maybe fail or return bogus data) */ Object value; try { if (t == JsonToken.VALUE_NULL) { value = valueDes.getNullValue(ctxt); } else if (typeDeser == null) { value = valueDes.deserialize(jp, ctxt); } else { value = valueDes.deserializeWithType(jp, ctxt, typeDeser); } } catch (Exception e) { wrapAndThrow(e, result, keyName); return null; } result.put(key, value); } return result; }
static { tagFieldToID3v1Field.put(FieldKey.ARTIST, ID3v1FieldKey.ARTIST); tagFieldToID3v1Field.put(FieldKey.ALBUM, ID3v1FieldKey.ALBUM); tagFieldToID3v1Field.put(FieldKey.TITLE, ID3v1FieldKey.TITLE); tagFieldToID3v1Field.put(FieldKey.TRACK, ID3v1FieldKey.TRACK); tagFieldToID3v1Field.put(FieldKey.YEAR, ID3v1FieldKey.YEAR); tagFieldToID3v1Field.put(FieldKey.GENRE, ID3v1FieldKey.GENRE); tagFieldToID3v1Field.put(FieldKey.COMMENT, ID3v1FieldKey.COMMENT); }
private void readShaderDefinition( Shader.ShaderType shaderType, String name, String... languages) { shaderNames.put(shaderType, name); if (langSize != 0 && langSize != languages.length) { throw new AssetLoadException( "Technique " + technique.getName() + " must have the same number of languages for each shader type."); } langSize = languages.length; for (int i = 0; i < languages.length; i++) { if (i >= shaderLanguages.size()) { shaderLanguages.add(new EnumMap<Shader.ShaderType, String>(Shader.ShaderType.class)); } shaderLanguages.get(i).put(shaderType, languages[i]); } }
public LocalizationServiceImpl() { localizationAlgorithms.put(LocalizationType.ByBestError, new ByBestError()); localizationAlgorithms.put(LocalizationType.ByErrorAverage, new ByErrorAverage()); }
public static void load() { final FileConfiguration config = UDSPlugin.getPlugin().getConfig(); BLOCK_CREEPERS = config.getBoolean("block.creeper"); BLOCK_ENDERMEN = config.getBoolean("block.endermen"); BLOCK_SILVERFISH = config.getBoolean("block.silverfish"); BLOCK_TNT = config.getBoolean("block.tnt"); BLOCK_WITHER = config.getBoolean("block.wither"); MAP_DATA = (byte) config.getInt("map-data"); BASE_COST = config.getInt("cost.base"); BUILD_COST = config.getInt("cost.build"); CITY_COST = config.getInt("cost.city"); CLAN_COST = config.getInt("cost.clan"); EXPAND_COST = config.getInt("cost.expand"); HOME_COST = config.getInt("cost.home"); MAP_COST = config.getInt("cost.map"); SHOP_COST = config.getInt("cost.shop"); VIP_COST = config.getInt("cost.vip"); UNDO_COUNT = config.getInt("range.undo"); DRAIN_RANGE = config.getInt("range.drain"); MOVE_RANGE = config.getInt("range.move"); EDIT_RANGE = config.getInt("range.edit"); COMPASS_RANGE = config.getInt("range.compass"); BUTCHER_RANGE = config.getInt("range.butcher"); VIP_SPAWNS = config.getInt("vip.spawns"); WORLD_BORDER = config.getInt("range.world"); WORLD_BORDER_SQRD = WORLD_BORDER * WORLD_BORDER; SPAWNER_EXP = config.getInt("exp.spawner"); REQUEST_TTL = config.getLong("request-timeout") * TimeUtils.SECOND; MINECART_TTL = config.getLong("minecart.life") * TimeUtils.SECOND; PVP_TIME = config.getLong("pvp-time") * TimeUtils.SECOND; SLOW_TIME = config.getLong("auto-save") * TimeUtils.MINUTE; DRAGON_RESPAWN = config.getLong("respawn-dragon") * TimeUtils.MINUTE; VIP_TIME = config.getLong("vip.time") * TimeUtils.DAY; CURRENCIES = config.getString("currency.plural"); WELCOME_MSG = config.getString("welcome.message"); WELCOME_ADMIN = config.getString("welcome.admin"); SERVER_OWNER = config.getString("server-owner"); CURRENCY = config.getString("currency.singular"); MAIN_WORLD = config.getString("world-name"); WELCOME_GIFT = Material.getMaterial(config.getString("welcome.gift")); if (WELCOME_GIFT == null) WELCOME_GIFT = Material.EMERALD; SERVER_RULES = config.getStringList("server-rules"); PISTON_POWER = config.getDouble("piston-power"); SHARES = config.getStringList("inventory-shares"); GMAIL_ADDRESS = config.getString("gmail.email"); SKULL = config.getDouble("head-drop-chance"); GMAIL_PASSWORD = config.getString("gmail.password"); VIP_WHITELIST.clear(); for (int typeId : config.getIntegerList("item-whitelist")) { VIP_WHITELIST.add(Material.getMaterial(typeId)); } KITS.clear(); for (String kit : config.getStringList("kits")) { final String[] kitSplit = kit.split(","); final List<ItemStack> items = new ArrayList<ItemStack>(ArrayUtils.subarray(kitSplit, 3, kitSplit.length - 1).length); for (Object item : ArrayUtils.subarray(kitSplit, 3, kitSplit.length - 1)) { items.add(new ItemStack(Material.getMaterial(Integer.parseInt((String) item)))); } KITS.add( new Kit( kitSplit[0], Integer.parseInt(kitSplit[1]), items, PlayerRank.getByName(kitSplit[2]))); } MOB_REWARDS.clear(); for (EntityType entityType : EntityType.values()) { String entityName = "mob-rewards." + entityType.getName(); if (entityName != null) { entityName = entityName.toLowerCase(); MOB_REWARDS.put(entityType, config.getInt(entityName)); } } GLOBAL_FLAGS.clear(); for (RegionFlag flag : RegionFlag.values()) { final String flagname = "global-flags." + flag.toString().toLowerCase(); GLOBAL_FLAGS.put(flag, config.getBoolean(flagname)); } }
private void addCatItem(String str, Cat cat) { categories.put(cat, categoryBox.getItemCount()); categoryBox.addItem(str); }
private void addConItem(String str, Con con) { conspicuities.put(con, conBox.getItemCount()); conBox.addItem(str); }
private void addReflItem(String str, Con con) { reflectivities.put(con, reflBox.getItemCount()); reflBox.addItem(str); }
private void addStsItem(String str, Sts sts) { statuses.put(sts, statusBox.getItemCount()); statusBox.addItem(str); }
private void addCnsItem(String str, Cns cns) { constructions.put(cns, constrBox.getItemCount()); constrBox.addItem(str); }
private void addMorItem(String str, Cat cat) { moorings.put(cat, mooringBox.getItemCount()); mooringBox.addItem(str); }
/** * Programa principal para o projeto 2. * * @param args argumentos da linha de comando. */ public static void main(String[] args) { // Faz o parsing dos argumentos da linha de comando. GetOpt options = new GetOpt("Projeto2", args, "vr"); int opt; while ((opt = options.nextOpt()) != -1) { switch (opt) { default: usage(); break; case 'v': verbose = true; break; case 'r': rand = new Random(0); break; } } if (rand == null) { rand = new Random(); } if (options.optind != args.length - 2) { usage(); } alambiqueCount = Integer.parseInt(args[options.optind]); int iteracoes = Integer.parseInt(args[options.optind + 1]); // Cria os atravessadores atravessadores = new EnumMap<Cana, Atravessador>(Cana.class); for (Cana g : Cana.values()) { // Voc� precisa implementar a classe AtravessadorImpl para o programa funcionar. atravessadores.put(g, new AtravessadorImpl(g)); } // Criar o �nico fornecedor. fornecedor = new Fornecedor(iteracoes); Thread threadFornecedor = new Thread(fornecedor, "Fornecedor"); alambiques = new Alambique[alambiqueCount]; alambiqueThreads = new Thread[alambiqueCount]; for (int i = 0; i < alambiqueCount; i++) { alambiques[i] = new Alambique(); alambiqueThreads[i] = new Thread(alambiques[i], "Alambique " + i); } // Inicia os threads // Todos eles tem prioridade mais baixa que o thread pricniapl ent�o nenhum deles // come�ar� a rodar antes que todos tenham sidos inicializados. threadFornecedor.setPriority(Thread.NORM_PRIORITY - 1); threadFornecedor.start(); for (Thread t : alambiqueThreads) { t.setPriority(Thread.NORM_PRIORITY - 1); t.start(); } // Espera que todos os threads sejam finalizados try { // O thread do fornecedor ser� finalizado quando ele concluir todas as itera��es // especificadas. threadFornecedor.join(); // Espera 3 segundos para dar uma chance para os threads do alambique terminarem // depois disso, todos que n�o finalizarem ser�o interrompidos. Thread.sleep(3000); for (Thread t : alambiqueThreads) { t.interrupt(); t.join(); } } catch (InterruptedException e) { e.printStackTrace(); } // imprime o estado final out.printf("**** Finalizando%n"); Pedido quant; Pedido balanco = new Pedido(); int produzido = 0; int nosAtravessadores = 0; int consumido = 0; quant = fornecedor.getProducao(); out.printf("Produzido %s%n", quant); for (Cana g : Cana.values()) { int n = quant.get(g); balanco.troca(g, n); produzido += n; } for (Cana g : Cana.values()) { quant = atravessadores.get(g).getEstoqueDisponivel(); for (Cana c1 : Cana.values()) { int n = quant.get(c1); balanco.troca(c1, -n); nosAtravessadores += n; } } for (int i = 0; i < alambiqueCount; i++) { quant = alambiques[i].getConsumo(); out.printf("O Alambique %d consumiu %s%n", i, quant); for (Cana g : Cana.values()) { int n = quant.get(g); balanco.troca(g, -n); consumido += n; } } out.printf("O balan�o final � %s%n", balanco); out.printf( "Total: produzido = %d, consumido = %d," + " sobrando nos atravessadores = %d, liquido = %d%n", produzido, consumido, nosAtravessadores, (produzido - consumido - nosAtravessadores)); } // main(String[])
public synchronized void increaseStock(Book book, int quantity, int jobSeqNum) { if (inventory.containsKey(book)) inventory.put(book, inventory.get(book) + quantity); else inventory.put(book, quantity); printWork(true, jobSeqNum, book, inventory.get(book) - quantity, inventory.get(book)); notifyAll(); }
private void transition(JsonToken token, State state) { transitions.put(token, state); }
public void addHL7OrderSPSStatus(HL7OrderSPSStatus rule) { hl7OrderSPSStatuses.put(rule.getSPSStatus(), rule); }
public void addIDGenerator(IDGenerator generator) { idGenerators.put(generator.getName(), generator); }
public void setAttributeFilter(Entity entity, AttributeFilter filter) { attributeFilters.put(entity, filter); }