public static List<Uploader> getUnsyncCopy_uploadList() {
   synchronized (uploadList) {
     ArrayList<Uploader> uploadList2 = new ArrayList<Uploader>();
     Collections.copy(uploadList, uploadList2);
     return uploadList2;
   }
 }
  /** initialize this definition with the other, sort of like a copy constructor */
  public void initializeFrom(WidgetDefinition definition) throws Exception {
    super.initializeFrom(definition);

    if (definition instanceof AggregateFieldDefinition) {
      AggregateFieldDefinition other = (AggregateFieldDefinition) definition;

      this.combineExpr = other.combineExpr;
      this.splitRegexp = other.splitRegexp;
      this.splitPattern = other.splitPattern;
      this.splitFailMessage = other.splitFailMessage;

      Iterator defs = other.container.getWidgetDefinitions().iterator();
      while (defs.hasNext()) {
        container.addWidgetDefinition((WidgetDefinition) defs.next());
      }

      Collections.copy(this.splitMappings, other.splitMappings);

      Iterator fields = other.mappedFields.iterator();
      while (fields.hasNext()) {
        this.mappedFields.add(fields.next());
      }

    } else {
      throw new Exception(
          "Definition to inherit from is not of the right type! (at " + getLocation() + ")");
    }
  }
Example #3
0
 public List<TangibleObject> getDefendersListClone() {
   synchronized (objectMutex) {
     List<TangibleObject> returnList = new Vector<TangibleObject>();
     Collections.copy(returnList, defendersList);
     return returnList;
   }
 }
Example #4
0
  public static void main(String[] args) {

    List src1 = new ArrayList(3);
    src1.add("a");
    src1.add("b");
    src1.add("c");

    List des1 = new ArrayList(3);
    System.out.println(des1.size()); // 是0,而不是3.只有在add或者remove时才会改变,3只代表它的容纳能力是3,而非大小
    Collections.copy(des1, src1);
  }
 public void resumeSuggestionOnLastComposedWord(final LastComposedWord lastComposedWord) {
   mEvents.clear();
   Collections.copy(mEvents, lastComposedWord.mEvents);
   mInputPointers.set(lastComposedWord.mInputPointers);
   mCombinerChain.reset();
   refreshTypedWordCache();
   mCapitalizedMode = lastComposedWord.mCapitalizedMode;
   mAutoCorrection = null; // This will be filled by the next call to updateSuggestion.
   mCursorPositionWithinWord = mCodePointSize;
   mRejectedBatchModeSuggestion = null;
   mIsResumed = true;
 }
Example #6
0
  public static void main(String[] args) {

    // ̽¾¿copyµÄdz¸´ÖÆ
    List<String> list1 = Arrays.asList("red", "green", "blue");
    List<String> list2 = Arrays.asList("pink", "sdfdsf");

    Collections.copy(list1, list2);
    System.out.println(list1);
    System.out.println(list2);
    list2.set(0, "brown");
    System.out.println(list1);
    System.out.println(list2);
  }
 /**
  * Gets the list activities from response.
  *
  * @param response
  * @return
  */
 private List<RestActivity> getListActivitiesFromResponse(HttpResponse response) {
   try {
     JSONObject jsonObject = (JSONObject) JSONValue.parse(getContent(response));
     JSONArray jsonArray = (JSONArray) jsonObject.get("activities");
     List<RestActivity> activities =
         SocialJSONDecodingSupport.JSONArrayObjectParser(
             RestActivity.class, jsonArray.toJSONString());
     List<RestActivity> copyRestActivities = new ArrayList(activities);
     Collections.copy(copyRestActivities, activities);
     return copyRestActivities;
   } catch (Exception e) {
     throw new ServiceException(ActivityService.class, "invalid response", null);
   }
 }
Example #8
0
  static void CollectionsCopy() {
    List<Person> srcList = new ArrayList<Person>();
    Person p1 = new Person(20, "123");
    Person p2 = new Person(21, "ABC");
    Person p3 = new Person(22, "abc");
    srcList.add(p1);
    srcList.add(p2);
    srcList.add(p3);
    List<Person> destList = new ArrayList<Person>(Arrays.asList(new Person[srcList.size()]));

    Collections.copy(destList, srcList);

    MyListUtils.printList(destList);
    srcList.get(0).setAge(100);
    MyListUtils.printList(destList);
  }
Example #9
0
  public ArrayList<Point> quickHull(ArrayList<Point> points) {
    final ArrayList<Point> convexHull = new ArrayList<Point>();
    if (points.size() < 3) {
      ArrayList<Point> clonedList = new ArrayList<>();
      Collections.copy(clonedList, points);
      return clonedList;
    }

    int minPoint = -1, maxPoint = -1;
    int minX = Integer.MAX_VALUE;
    int maxX = Integer.MIN_VALUE;
    for (int i = 0; i < points.size(); i++) {
      if (points.get(i).x < minX) {
        minX = points.get(i).x;
        minPoint = i;
      }
      if (points.get(i).x > maxX) {
        maxX = points.get(i).x;
        maxPoint = i;
      }
    }
    final Point a = points.get(minPoint);
    final Point b = points.get(maxPoint);
    convexHull.add(a);
    convexHull.add(b);
    points.remove(a);
    points.remove(b);

    ArrayList<Point> leftSet = new ArrayList<Point>();
    ArrayList<Point> rightSet = new ArrayList<Point>();

    for (int i = 0; i < points.size(); i++) {
      Point p = points.get(i);
      if (pointLocation(a, b, p) == -1) leftSet.add(p);
      else rightSet.add(p);
    }
    hullSet(a, b, rightSet, convexHull);
    hullSet(b, a, leftSet, convexHull);

    return convexHull;
  }
 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);
 }
Example #11
0
File: Graph.java Project: AKSW/SINA
 public void setEntityList(List<Entity> i) {
   Collections.copy(EntityList, i);
 }
Example #12
0
  /** @throws Exception */
  private static void displayStats() throws Exception {
    String[][] statsList = getCounters();
    ManagedObjectReference hostmor = getHostByHostName(hostname);
    if (hostmor == null) {
      System.out.println("Host Not Found");
      return;
    }

    Object property;
    ArrayList props = (ArrayList) getDynamicProperty(perfManager, "perfCounter");

    if (props != null && props.size() > 0) {
      property = props.get(0);
    } else {
      property = null;
    }

    // ArrayOfPerfCounterInfo arrayCounter = (ArrayOfPerfCounterInfo) property;
    ArrayList counterInfoList = new ArrayList();
    counterInfoList.add(property);

    List<PerfMetricId> midVector = new ArrayList<PerfMetricId>();
    List<String> statNames = new ArrayList<String>();
    for (int i = 0; i < statsList.length; i++) {
      PerfCounterInfo counterInfo =
          getCounterInfo(counterInfoList, statsList[i][0], statsList[i][1]);
      if (counterInfo == null) {
        System.out.println(
            "Warning: Unable to find stat " + statsList[i][0] + " " + statsList[i][1]);
        continue;
      }
      String counterName = counterInfo.getNameInfo().getLabel();
      statNames.add(counterName);

      PerfMetricId pmid = new PerfMetricId();
      pmid.setCounterId(counterInfo.getKey());
      pmid.setInstance("");
      midVector.add(pmid);
    }
    List<PerfMetricId> midList = new ArrayList<PerfMetricId>(midVector);
    Collections.copy(midList, midVector);

    PerfQuerySpec spec = new PerfQuerySpec();
    spec.setEntity(hostmor);

    GregorianCalendar startTime = new GregorianCalendar();
    startTime.add(Calendar.SECOND, -60);

    XMLGregorianCalendar starttimexmlgc =
        DatatypeFactory.newInstance().newXMLGregorianCalendar(startTime);

    // spec.setStartTime(starttimexmlgc);
    spec.getMetricId().addAll(midList);
    spec.setIntervalId(new Integer(20));
    querySpec = spec;

    final List<String> statNames2 = statNames;
    javax.swing.SwingUtilities.invokeLater(
        new Runnable() {

          public void run() {
            createAndShowGUI("VM Name", statNames2);
          }
        });

    Timer timer = new Timer(true);
    timer.schedule(
        new TimerTask() {

          public void run() {
            refreshStats();
          }
        },
        1000,
        21000);
  }
  /** @throws Exception */
  public void testCreateStuctureWithSynonymsRenameAndReverseIt() throws Exception {
    // Create A/A/A/A/A ... 10 time
    // reverse
    startNewTransaction();
    ArrayList<TransferManifestNode> copy = new ArrayList<TransferManifestNode>();

    try {
      String transferId = ftTransferReceiver.start("1234", true, ftTransferReceiver.getVersion());

      try {
        NodeRef parent = companytHome;
        staticNodes = new ArrayList<TransferManifestNode>();
        staticNodes2 = new ArrayList<TransferManifestNode>();
        for (int i = 1; i <= 20; i++) {
          TransferManifestNormalNode folderNode = this.createFolderNode(parent, "A");
          staticNodes.add(folderNode);
          String fName = "F_" + i;
          TransferManifestNormalNode folderNode2 =
              this.createFolderNode(folderNode.getNodeRef(), fName);
          staticNodes2.add(folderNode2);
          parent = folderNode.getNodeRef();
        }

        copy = copyList(staticNodes);
        Collections.copy(copy, staticNodes);
        copy.addAll(staticNodes2);
        // transferring node in random order
        Collections.shuffle(copy);

        String snapshot = createSnapshot(copy, false);
        ftTransferReceiver.setFileTransferRootNodeFileFileSystem(this.companytHome.toString());
        ftTransferReceiver.saveSnapshot(
            transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
        ftTransferReceiver.commit(transferId);

      } catch (Exception ex) {
        ftTransferReceiver.end(transferId);
        throw ex;
      }
    } finally {
      endTransaction();
    }
    // check that the temporary folder where orphan are put in do not exist anymore
    File tempFolder =
        new File(ftTransferReceiver.getDefaultReceivingroot() + "/" + "T_V_R_1234432123478");
    assertFalse(tempFolder.exists());

    String curPath = ftTransferReceiver.getDefaultReceivingroot();
    for (int i = 1; i <= 20; i++) {
      String curPath1 = curPath + "/" + "A";
      File transferedNode = new File(curPath1);
      assertTrue(transferedNode.exists());
      String curPath2 = curPath1 + "/" + "F_" + i;
      transferedNode = new File(curPath2);
      assertTrue(transferedNode.exists());
      curPath += "/" + "A";
    }

    // reverse the structure
    Collections.reverse(staticNodes);

    // modify the parents
    NodeRef parent = companytHome;
    for (int i = 0; i < 20; i++) {
      TransferManifestNormalNode curNode = (TransferManifestNormalNode) staticNodes.get(i);
      modifyParentNode(parent, curNode);
      parent = curNode.getNodeRef();
    }

    staticNodes.addAll(staticNodes2);

    try {
      String transferId = ftTransferReceiver.start("1234", true, ftTransferReceiver.getVersion());

      try {

        // transferring node in random order
        Collections.shuffle(copy);

        String snapshot = createSnapshot(copy, false);
        ftTransferReceiver.setFileTransferRootNodeFileFileSystem(this.companytHome.toString());
        ftTransferReceiver.saveSnapshot(
            transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
        ftTransferReceiver.commit(transferId);

      } catch (Exception ex) {
        ftTransferReceiver.end(transferId);
        throw ex;
      }
    } finally {
      endTransaction();
    }

    // check result on file system
    curPath = ftTransferReceiver.getDefaultReceivingroot();
    for (int i = 20; i > 0; i--) {
      String curPath1 = curPath + "/" + "A";
      File transferedNode = new File(curPath1);
      assertTrue(transferedNode.exists());
      String curPath2 = curPath1 + "/" + "F_" + i;
      transferedNode = new File(curPath2);
      assertTrue(transferedNode.exists());
      curPath += "/" + "A";
    }
  }
Example #14
0
File: Graph.java Project: AKSW/SINA
 public void setTripleList(List<TriplePattern> i) {
   Collections.copy(TripleList, i);
 }
Example #15
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();
  }
  @Test
  public void test() {
    List<String> worker = new ArrayList<String>();
    worker.add("Sunny");
    worker.add("Edition");
    worker.add("Clinton");

    // 排序
    Collections.sort(worker);
    System.out.println(worker);

    // 二分法查找,必须先排序
    int index = Collections.binarySearch(worker, "Sunny");
    System.out.println("binary search index=" + index);

    // 复制,目标列表的个数必须大于等于源列表的个数,此方法比较鸡肋
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    Collections.copy(list, worker);
    System.out.println("list is " + list);

    // 替换
    Collections.fill(list, "A");
    System.out.println("list after fill A is " + list);

    // 返回指定 collection 中等于指定对象的元素数
    int times = Collections.frequency(list, "A");
    System.out.println("A frequency is  " + times);

    // 获取最大最小数据
    System.out.println("min data of worker is " + Collections.min(worker));
    System.out.println("max data of worker is " + Collections.max(worker));

    // 复制多次
    list = Collections.nCopies(10, "default");
    System.out.println("nCopies list is " + list);

    // 反转
    Collections.reverse(worker);
    System.out.println("reverse worker is " + worker);

    // 打乱顺序
    Collections.shuffle(worker);
    System.out.println("shuffle worker is " + worker);

    // 包含指定对象的Set
    Set<String> set = new HashSet<String>(Collections.singleton("sunny"));
    System.out.println("singleton set " + set);

    // 包含指定对象的List
    list = new ArrayList<String>(Collections.singletonList("sunny"));
    System.out.println("singletonList is " + list);

    // 包含指定键值对的Map
    Map<String, String> map = new HashMap<String, String>(Collections.singletonMap("key", "value"));
    System.out.println("singletonMap is " + map);

    // 交换指定位置的元素
    Collections.swap(worker, 0, 1);
    System.out.println("after swap worker is " + worker);
  }
  public void testLinkedListOperations() throws Exception {

    List<Integer> numbers = new LinkedList<>(Arrays.asList(0, 1, 2, 3, 4));

    assertEquals(5, numbers.size());

    for (int i = 0; i < numbers.size(); i++) {
      assertEquals(i, (int) numbers.get(i));
    }

    numbers.add(2, 10);
    assertEquals(10, (int) numbers.get(2));

    Collections.sort(numbers);
    assertEquals(10, (int) numbers.get(numbers.size() - 1));

    int index = Collections.binarySearch(numbers, 10);
    assertEquals(5, index);

    System.out.println("Before shuffle:");

    for (Integer i : numbers) {
      System.out.print(i + " ");
    }

    Collections.shuffle(numbers);

    System.out.println("\nAfter shuffle:");

    for (int i : numbers) {
      System.out.print(i + " ");
    }

    Collections.sort(numbers);
    Collections.reverse(numbers);

    assertEquals(10, (int) numbers.get(0));
    assertEquals(0, (int) numbers.get(numbers.size() - 1));

    int max = Collections.max(numbers);
    assertEquals(10, max);

    int min = Collections.min(numbers);
    assertEquals(0, min);

    List<Integer> copy = Arrays.asList(0, 0, 0, 0, 0, 0);
    Collections.copy(copy, numbers);

    for (int i = 0; i < copy.size(); i++) {
      assertEquals((int) copy.get(i), (int) numbers.get(i));
    }

    Collections.fill(numbers, 100);

    for (int i : numbers) {
      assertEquals(100, i);
    }

    numbers = new LinkedList<>(Arrays.asList(0, 1, 2, 3, 4, 1));
    int frequency = Collections.frequency(numbers, 1);
    assertEquals(2, frequency);

    copy = Arrays.asList(0, 0, 0, 0, 0, 0);
    boolean disjoint = Collections.disjoint(numbers, copy);
    assertFalse(disjoint);

    copy = Arrays.asList(100, 101, 102);
    disjoint = Collections.disjoint(numbers, copy);
    assertTrue(disjoint);
  }