Пример #1
0
 public static void main(String[] args) {
   ArrayList nums = new ArrayList();
   nums.add(2);
   nums.add(-5);
   nums.add(3);
   nums.add(0);
   // 输出:[2, -5, 3, 0]
   System.out.println(nums);
   // 输出最大元素,将输出3
   System.out.println(Collections.max(nums));
   // 输出最小元素,将输出-5
   System.out.println(Collections.min(nums));
   // 将nums中的0使用1来代替
   Collections.replaceAll(nums, 0, 1);
   // 输出:[2, -5, 3, 1]
   System.out.println(nums);
   // 判断-5 在List集合中出现的次数,返回1
   System.out.println(Collections.frequency(nums, -5));
   // 对nums集合排序
   Collections.sort(nums);
   // 输出:[-5, 1, 2, 3]
   System.out.println(nums);
   // 只有排序后的List集合才可用二分法查询,输出3
   System.out.println(Collections.binarySearch(nums, 3));
 }
Пример #2
0
  @Override
  public Movie update(Movie movie) {
    // TODO Auto-generated method stub

    for (Movie mov : movielist) {
      if (mov.getId().equals(movie.getId())) {
        Collections.replaceAll(movielist, mov, movie);
      } else throw new IllegalArgumentException("This movie is not present in the list");
    }
    if (movielist.contains(movie)) return movie;
    else return null;
  }
Пример #3
0
    public static int countUniqueValues(Map<String, Integer> map) {
      int cnt = 0;
      ArrayList<Integer> valueList = new ArrayList<Integer>(map.values());
      for (Integer val : valueList) {
        if (val != -Integer.MAX_VALUE) {
          Collections.replaceAll(valueList, val, -Integer.MAX_VALUE);
          cnt++;
        }
      }

      return cnt;
    }
 public void addSubBuild(SubBuild subBuild) {
   String key =
       subBuild
           .getPhaseName()
           .concat(subBuild.getJobName())
           .concat(String.valueOf(subBuild.getBuildNumber()));
   if (subBuildsMap.containsKey(key)) {
     SubBuild e = subBuildsMap.get(key);
     Collections.replaceAll(getSubBuilds(), e, subBuild);
   } else {
     getSubBuilds().add(subBuild);
   }
   subBuildsMap.put(key, subBuild);
 }
Пример #5
0
  public static void replaceTheValueOfExistingElementInArrayList() {

    ArrayList<String> strings = new ArrayList<String>(200);

    strings.add("a");
    strings.add("b");
    strings.add("c");
    strings.add("d");
    strings.add("b");

    strings.set(2, "z");

    Collections.replaceAll(strings, "b", "z");
  }
Пример #6
0
 public static void main(String[] args) {
   print(list);
   print(
       "'list' disjoint (Four)?: "
           + Collections.disjoint(list, Collections.singletonList("Four")));
   print("max: " + Collections.max(list));
   print("min: " + Collections.min(list));
   print("max w/ comparator: " + Collections.max(list, String.CASE_INSENSITIVE_ORDER));
   print("min w/ comparator: " + Collections.min(list, String.CASE_INSENSITIVE_ORDER));
   List<String> sublist = Arrays.asList("Four five six".split(" "));
   print("indexOfSubList: " + Collections.indexOfSubList(list, sublist));
   print("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist));
   Collections.replaceAll(list, "one", "Yo");
   print("replaceAll: " + list);
   Collections.reverse(list);
   print("reverse: " + list);
   Collections.rotate(list, 3);
   print("rotate: " + list);
   List<String> source = Arrays.asList("in the matrix".split(" "));
   Collections.copy(list, source);
   print("copy: " + list);
   Collections.swap(list, 0, list.size() - 1);
   print("swap: " + list);
   Collections.shuffle(list, new Random(47));
   print("shuffled: " + list);
   Collections.fill(list, "pop");
   print("fill: " + list);
   print("frequency of 'pop': " + Collections.frequency(list, "pop"));
   List<String> dups = Collections.nCopies(3, "snap");
   print("dups: " + dups);
   print("'list' disjoint 'dups'?: " + Collections.disjoint(list, dups));
   // Getting an old-style Enumeration:
   Enumeration<String> e = Collections.enumeration(dups);
   Vector<String> v = new Vector<String>();
   while (e.hasMoreElements()) v.addElement(e.nextElement());
   // Converting an old-style Vector
   // to a List via an Enumeration:
   ArrayList<String> arrayList = Collections.list(v.elements());
   print("arrayList: " + arrayList);
 }
Пример #7
0
 public static Geometry replace(Geometry parent, Geometry original, Geometry replacement) {
   List elem = extractElements(parent, false);
   Collections.replaceAll(elem, original, replacement);
   return parent.getFactory().buildGeometry(elem);
 }
Пример #8
0
  public static void main(String args[]) throws FileNotFoundException, IOException {
    System.out.println("Gathering data...");
    // Use char[] for ease in building strings, despite only using 8 bits.
    int numElements = 65536;
    char[] info = new char[numElements];
    for (int i = 0; i < info.length; i++) {
      if (i == '\n' || i == '\r') info[i] = NEWLINE_CODE;
      else if (i == ' ' || i == '\t' || i == '\f') info[i] = SPACE_CODE;
      else if (i < 128 && Character.isLowerCase((char) i)) info[i] = LOWER_CODE; // Ascii lower case
      else if (i < 128 && Character.isUpperCase((char) i)) info[i] = UPPER_CODE; // Ascii upper case
      else if (i < 128 && Character.isDigit((char) i)) info[i] = DIGIT_CODE; // Ascii digit
      else if (Character.isJavaIdentifierStart((char) i)) info[i] = OTHER_LETTER_CODE;
      else if (Character.isJavaIdentifierPart((char) i)) info[i] = OTHER_DIGIT_CODE;
      else {
        info[i] = BAD_CODE;
        numElements--;
      }
    }

    System.out.println("Compressing tables...");
    int bestShift = 0;
    int bestEst = info.length;
    String bestBlkStr = null;

    for (int i = 3; i < 11; i++) {
      int blkSize = 1 << i;
      Map blocks = new HashMap();
      List blkArray = new ArrayList();
      System.out.print("shift: " + i);

      for (int j = 0; j < info.length; j += blkSize) {
        String key = new String(info, j, blkSize);
        if (blocks.get(key) == null) {
          blkArray.add(key);
          blocks.put(key, new Integer(blkArray.size()));
        }
      }
      int blkNum = blkArray.size();
      int blockLen = blkNum * blkSize;
      System.out.print(" before " + blockLen);

      //
      // Try to pack blkArray, by finding successively smaller matches
      // between heads and tails of blocks.
      //
      for (int j = blkSize - 1; j > 0; j--) {
        Map tails = new HashMap();
        for (int k = 0; k < blkArray.size(); k++) {
          String str = (String) blkArray.get(k);
          if (str == null) continue;
          String tail = str.substring(str.length() - j);
          List l = (List) tails.get(tail);
          if (l == null) tails.put(tail, new LinkedList(Collections.singleton(new Integer(k))));
          else l.add(new Integer(k));
        }

        //
        // Now calculate the heads, and merge overlapping blocks
        //
        block:
        for (int k = 0; k < blkArray.size(); k++) {
          String tomerge = (String) blkArray.get(k);
          if (tomerge == null) continue;
          while (true) {
            String head = tomerge.substring(0, j);
            LinkedList entry = (LinkedList) tails.get(head);
            if (entry == null) continue block;
            Integer other = (Integer) entry.removeFirst();
            if (other.intValue() == k) {
              if (entry.size() > 0) {
                entry.add(other);
                other = (Integer) entry.removeFirst();
              } else {
                entry.add(other);
                continue block;
              }
            }
            if (entry.size() == 0) tails.remove(head);

            //
            // A match was found.
            //
            String merge = blkArray.get(other.intValue()) + tomerge.substring(j);
            blockLen -= j;
            blkNum--;
            if (other.intValue() < k) {
              blkArray.set(k, null);
              blkArray.set(other.intValue(), merge);
              String tail = merge.substring(merge.length() - j);
              List l = (List) tails.get(tail);
              Collections.replaceAll(l, new Integer(k), other);
              continue block;
            }
            blkArray.set(k, merge);
            blkArray.set(other.intValue(), null);
            tomerge = merge;
          }
        }
      }
      StringBuffer blockStr = new StringBuffer(blockLen);
      for (int k = 0; k < blkArray.size(); k++) {
        String str = (String) blkArray.get(k);
        if (str != null) blockStr.append(str);
      }
      if (blockStr.length() != blockLen) throw new Error("Unexpected blockLen " + blockLen);
      int estimate = blockLen + (info.length >> (i - 1));
      System.out.println(" after merge " + blockLen + ": " + estimate + " bytes");
      if (estimate < bestEst) {
        bestEst = estimate;
        bestShift = i;
        bestBlkStr = blockStr.toString();
      }
    }

    int blkSize = 1 << bestShift;
    char[] blocks = new char[info.length / blkSize];
    for (int j = 0; j < info.length; j += blkSize) {
      String key = new String(info, j, blkSize);
      int index = bestBlkStr.indexOf(key);
      if (index == -1) throw new Error("Unexpected index for " + j);
      blocks[j >> bestShift] = (char) (index - j);
    }

    //
    // Process the code.h file
    //
    System.out.println("Generating code.h with shift of " + bestShift);
    PrintStream hfile = new PrintStream(new FileOutputStream("code.h"));
    printHeader(hfile, new String[] {"\"platform.h\""});
    hfile.println("#ifndef code_INCLUDED");
    hfile.println("#define code_INCLUDED");
    hfile.println();
    hfile.println("class Code");
    hfile.println("{");
    hfile.println("    //");
    hfile.println("    // To facilitate the scanning, the character set is partitioned into");
    hfile.println("    // 8 categories using the array CODE. These are described below");
    hfile.println("    // together with some self-explanatory functions defined on CODE.");
    hfile.println("    //");
    hfile.println("    enum {");
    hfile.println("        SHIFT = " + bestShift + ",");
    hfile.println("        NEWLINE_CODE = " + NEWLINE_CODE + ',');
    hfile.println("        SPACE_CODE = " + SPACE_CODE + ',');
    hfile.println("        BAD_CODE = " + BAD_CODE + ',');
    hfile.println("        DIGIT_CODE = " + DIGIT_CODE + ',');
    hfile.println("        OTHER_DIGIT_CODE = " + OTHER_DIGIT_CODE + ',');
    hfile.println("        LOWER_CODE = " + LOWER_CODE + ',');
    hfile.println("        UPPER_CODE = " + UPPER_CODE + ',');
    hfile.println("        OTHER_LETTER_CODE = " + OTHER_LETTER_CODE);
    hfile.println("    };");
    hfile.println();
    hfile.println("    static char codes[" + bestBlkStr.length() + "];");
    hfile.println("    static u2 blocks[" + blocks.length + "];");
    hfile.println();
    hfile.println();
    hfile.println("public:");
    hfile.println();
    hfile.println("    static inline void SetBadCode(wchar_t c)");
    hfile.println("    {");
    hfile.println("        codes[(u2) (blocks[c >> SHIFT] + c)] = BAD_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline void CodeCheck(wchar_t c)");
    hfile.println("    {");
    hfile.println("        assert((u2) (blocks[c >> SHIFT] + c) < " + bestBlkStr.length() + ");");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool CodeCheck(void)");
    hfile.println("    {");
    hfile.println("        for (int i = 0; i <= 0xffff; i++)");
    hfile.println("            CodeCheck((wchar_t) i);");
    hfile.println("        return true;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    //");
    hfile.println("    // \\r characters are replaced by \\x0a in Stream::ProcessInput().");
    hfile.println("    //");
    hfile.println("    static inline bool IsNewline(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return c == '\\x0a';");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsSpaceButNotNewline(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] == SPACE_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsSpace(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] <= SPACE_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsDigit(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] == DIGIT_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsOctalDigit(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return c >= U_0 && c <= U_7;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsHexDigit(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return c <= U_f && (c >= U_a ||");
    hfile.println("                            (c >= U_A && c <= U_F) ||");
    hfile.println("                            (c >= U_0 && c <= U_9));");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsUpper(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] == UPPER_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsLower(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] == LOWER_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsAlpha(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] >= LOWER_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("    static inline bool IsAlnum(wchar_t c)");
    hfile.println("    {");
    hfile.println("        return codes[(u2) (blocks[c >> SHIFT] + c)] >= DIGIT_CODE;");
    hfile.println("    }");
    hfile.println();
    hfile.println("};");
    hfile.println();
    hfile.println("#endif // code_INCLUDED");
    printFooter(hfile);
    hfile.close();

    //
    // Process the code.cpp file
    //
    System.out.println("Generating code.cpp");
    PrintStream cfile = new PrintStream(new FileOutputStream("code.cpp"));
    printHeader(cfile, new String[] {"\"code.h\""});
    cfile.println("char Code::codes[" + bestBlkStr.length() + "] =");
    cfile.println("{");
    for (int j = 0; j < bestBlkStr.length(); j += 4) {
      for (int k = 0; k < 4; k++) {
        if (k + j >= bestBlkStr.length()) break;
        if (k == 0) cfile.print("   ");
        cfile.print(" " + CODE_NAMES[bestBlkStr.charAt(k + j)] + ",");
      }
      cfile.println();
    }
    cfile.println("};");
    cfile.println();
    cfile.println();
    cfile.println("//");
    cfile.println("// The Blocks vector:");
    cfile.println("//");
    cfile.println("u2 Code::blocks[" + blocks.length + "] =");
    cfile.println("{");
    for (int k = 0; k < blocks.length; k += 9) {
      for (int i = 0; i < 9; i++) {
        if (k + i >= blocks.length) break;
        if (i == 0) cfile.print("   ");
        cfile.print(" 0x" + Integer.toHexString(blocks[k + i]) + ",");
      }
      cfile.println();
    }
    cfile.println("};");
    printFooter(cfile);
    cfile.close();

    //
    // Print statistics.
    //
    System.out.println(
        "Total static storage utilization is " + blocks.length * 2 + " bytes for block lookup");
    System.out.println("   plus " + bestBlkStr.length() + " bytes for the encodings");
    System.out.println(
        "The number of unicode characters legal in Java sourcecode is " + numElements);
  }
Пример #9
0
  public static void main(String[] args) {

    List<MyClass> list = new ArrayList<MyClass>();

    list.add(new MyClass("Василий"));
    list.add(new MyClass("Павел"));
    list.add(new MyClass("Андрей"));
    list.add(new MyClass("Андрей"));
    list.add(new MyClass("Петр"));
    list.add(new MyClass("Анжелика"));

    System.out.println("Оригинал");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Смешивание
    Collections.shuffle(list);
    System.out.println("Смешивание");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Обратный порядок
    Collections.reverse(list);
    System.out.println("Обратный порядок");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // "Проворачивание" на определенное количество
    Collections.rotate(list, 2); // Число может быть отрицательным - тогда порядок будет обратный
    System.out.println("Проворачивание");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Обмен элементов
    Collections.swap(list, 0, list.size() - 1);
    System.out.println("Обмен элементов");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Замена
    Collections.replaceAll(list, new MyClass("Андрей"), new MyClass("Алексей"));
    System.out.println("Замена");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Сортировка
    // Collections.sort(list);   // Этот запрос не пройдет т.к. класс MyClass
    // не реализует интерфейс Comparable
    System.out.println("Сортировка Comparable класса");
    List<MyClassCompare> listSort = new ArrayList<MyClassCompare>();
    System.out.println("Без сортировки");
    for (MyClass mc : list) {
      listSort.add(new MyClassCompare(mc.toString()));
      System.out.println("Item sort:" + mc);
    }
    Collections.sort(listSort);
    System.out.println("После сортировки");
    for (MyClassCompare mc : listSort) {
      System.out.println("Item sort:" + mc);
    }
    System.out.println();

    // Сортировка с классом Comparator
    System.out.println("Сортировка с Comparator");
    System.out.println("Без сортировки");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    Collections.sort(list, new MyClassComparator());
    System.out.println("После сортировки");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Копирование - здесь обязательно надо иметь нужные размеры
    List<MyClass> list2 = new ArrayList<MyClass>();
    // Поэтому заполняем список. Хоть чем-нибудь.
    for (MyClass mc : list) {
      list2.add(null);
    }
    // Компируем из правого аргумента в левый
    Collections.copy(list2, list);
    System.out.println("Копирование");
    for (MyClass mc : list2) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Полная замена
    Collections.fill(list2, new MyClass("Антон"));
    System.out.println("Полная замена");
    for (MyClass mc : list2) {
      System.out.println("Item:" + mc);
    }
    System.out.println();
  }