Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.archmage.toolbox;
- import java.util.ArrayList;
- import java.util.HashMap;
- public abstract class Unique {
- private final int id;
- private static HashMap<String, ArrayList<Integer>> register = new HashMap<>();
- private static final int START_ID = 1;
- public Unique() {
- String idClass = getIdCode();
- if(!register.containsKey(idClass)) {
- register.put(idClass, new ArrayList<>());
- }
- for(int i = START_ID; i < Integer.MAX_VALUE; ++i) {
- if(!register.get(idClass).contains(Integer.valueOf(i))) {
- register.get(idClass).add((id = i));
- return;
- }
- }
- // this should never happen
- throw new UnsupportedOperationException("no suitable id was available!");
- }
- protected abstract String getIdCode();
- public final String getId() {
- return getIdCode() + (id + "");
- }
- /**
- * Receives an "id" argument and parses it into an array of valid ids.
- *
- * Expected format is [idClass][rangeStart]-[rangeEnd]
- *
- * e.g. for idClass "d", the following inputs are valid:
- *
- * "d1" = returns "d1"
- * "d4-6" = returns ["d4", "d5", "d6"]
- * "all" = returns all ids for idClass "d"
- *
- * If a larger rangeEnd than highest id is specified, it will return all
- * from rangeStart to the highest id.
- *
- * It is assumed that idClass does not contain spaces, numerals or hyphens.
- *
- * @param input
- * @return
- */
- public static String[] getIdsFromRange(String input) {
- if(input == null) return null;
- if((input = input.trim()).isEmpty()) return null;
- String idClass = input.replaceAll("[0-9]", "").replaceAll("\\-", "");
- if(idClass.length() == 0) return null;
- if(!register.containsKey(idClass)) return null;
- ArrayList<String> output = new ArrayList<>();
- int[] integers;
- try {
- String[] temp = input.replaceAll(idClass, "").split("\\-");
- if(temp.length == 0) return null;
- int low = Integer.valueOf(temp[0]);
- int high = Integer.valueOf(temp[temp.length - 1]);
- integers = new int[high - low + 1];
- for(int i = low; i <= high; ++i) {
- integers[i - low] = i;
- }
- // was I high when I wrote this?!
- // integers = new int[temp.length];
- // for(int i = 0; i < temp.length; ++i)
- // integers[i] = Integer.valueOf(temp[i]);
- }
- catch(NumberFormatException nfe) {
- return null;
- }
- for(int i = integers[0]; i <= integers[integers.length - 1]; ++i) {
- if(register.get(idClass).contains(i)) {
- output.add(idClass + i);
- }
- else break;
- }
- return output.toArray(new String[0]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement