예제 #1
0
  /**
   * Сгенерировать файл pipeline.xml необходимый для запуска модуля через run.pl.
   *
   * @param moduleName - имя модуля.
   * @param runOptions - опции запуска.
   * @return - абсолютный путь к сгенерированному pipeline.xml.
   */
  public File generatePipeline_xml(String moduleName, ArrayList<Option> runOptions) {
    // Создаем новый файл pipeline.xml в новой директории
    DocumentBuilder builder = XMLDOMWorker.getDocumentBuilder();

    Document pipelineXmlDoc = builder.newDocument();
    Element pipelineElement = pipelineXmlDoc.createElement("pipeline");
    pipelineXmlDoc.appendChild(pipelineElement);
    {
      // Создается элемент <node ...>
      Element nodeElement = pipelineXmlDoc.createElement("node");
      nodeElement.setAttribute("name", moduleName + "_task");
      nodeElement.setAttribute("parent", "undef");
      nodeElement.setAttribute("program", moduleName);
      nodeElement.setAttribute("status", "undef");
      pipelineElement.appendChild(nodeElement);
      {
        ListIterator<IOFile> iter = null;
        // Помещаются input файлы
        iter = inputFiles.listIterator();
        while (iter.hasNext()) {
          IOFile curFile = iter.next();
          Element fileElement = pipelineXmlDoc.createElement("file");
          fileElement.setAttribute("id", curFile.getName());
          fileElement.setAttribute("value", curFile.getAbsolutePath());
          nodeElement.appendChild(fileElement);
        }
        // Помещаются output файлы
        iter = outputFiles.listIterator();
        while (iter.hasNext()) {
          IOFile curFile = iter.next();
          Element fileElement = pipelineXmlDoc.createElement("file");
          fileElement.setAttribute("id", curFile.getName());
          fileElement.setAttribute("value", curFile.getAbsolutePath());
          nodeElement.appendChild(fileElement);
        }

        // Помещаются опции
        ListIterator<Option> optionsIter = runOptions.listIterator();
        while (optionsIter.hasNext()) {
          Option curOption = optionsIter.next();
          Element optionElement = pipelineXmlDoc.createElement("option");
          optionElement.setAttribute("id", curOption.getId());
          optionElement.setAttribute("value", curOption.getValue());
          nodeElement.appendChild(optionElement);
        }
      }
    }
    XMLDOMWorker.writeTree(pipelineXmlDoc, pipeline_xml);
    return pipeline_xml;
  }
예제 #2
0
  void close() {
    try {
      if (mySelector != null) mySelector.close();
    } catch (IOException e) {
    }
    mySelector = null;

    // run down open connections and sockets.
    Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
    while (i.hasNext()) {
      try {
        i.next().close();
      } catch (IOException e) {
      }
    }

    // 29Sep09: We create an ArrayList of the existing connections, then iterate over
    // that to call unbind on them. This is because an unbind can trigger a reconnect,
    // which will add to the Connections HashMap, causing a ConcurrentModificationException.
    // XXX: The correct behavior here would be to latch the various reactor methods to return
    // immediately if the reactor is shutting down.
    ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
    Iterator<EventableChannel> i2 = Connections.values().iterator();
    while (i2.hasNext()) {
      EventableChannel ec = i2.next();
      if (ec != null) {
        conns.add(ec);
      }
    }
    Connections.clear();

    ListIterator<EventableChannel> i3 = conns.listIterator(0);
    while (i3.hasNext()) {
      EventableChannel ec = i3.next();
      eventCallback(ec.getBinding(), EM_CONNECTION_UNBOUND, null);
      ec.close();

      EventableSocketChannel sc = (EventableSocketChannel) ec;
      if (sc != null && sc.isAttached()) DetachedConnections.add(sc);
    }

    ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
    while (i4.hasNext()) {
      EventableSocketChannel ec = i4.next();
      ec.cleanup();
    }
    DetachedConnections.clear();
  }
예제 #3
0
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.parseselected);

    text = (TextView) findViewById(R.id.parsedtext);
    Intent intent = getIntent();
    customerOrder = (Order) intent.getSerializableExtra("com.example.quickserve.Order.class");

    burgers = customerOrder.getBurgers();
    toppings = customerOrder.getToppings();
    sides = customerOrder.getSides();
    ListIterator<String> it = burgers.listIterator();
    ListIterator<String> it2 = toppings.listIterator();
    ListIterator<String> it3 = sides.listIterator();
    String a = "enditem";
    while (!burgers.isEmpty()) {
      text.append("Burger: ");
      text.append(it.next()); // first one
      it.remove(); // remove it
      text.append(" "); // space

      text.append(it.next()); // second one
      it.remove(); // remove it
      text.append(" "); // space

      text.append(it.next()); // third one
      it.remove(); // remove it
      text.append(" "); // space
      text.append("\n");
      text.append("Toppings: ");
      while (!toppings.isEmpty()) {
        text.append(" "); // space
        String b = it2.next();
        it2.remove();
        if (b.compareTo(a) == 0) break;
        text.append(b);
      }
    } // end outter while
    text.append("\n");
    text.append("Sides: ");
    while (!sides.isEmpty()) {
      text.append(" "); // space
      String c = it3.next();
      it3.remove();
      text.append(c);
    }
  }
 @Override
 public void run() {
   try {
     boolean running = true;
     while (running) {
       try {
         // block on event availability
         ThreadBoundEvent event = queue.take();
         // add to the batch, and see if we can add more
         batch.add(event);
         if (maxBatchSize > 0) {
           queue.drainTo(batch, maxBatchSize);
         }
         // check for the stop condition (and remove it)
         // treat batches of 1 (the most common case) specially
         if (batch.size() > 1) {
           ListIterator<ThreadBoundEvent> itr = batch.listIterator();
           while (itr.hasNext()) {
             ThreadBoundEvent next = itr.next();
             if (next.getClass().equals(ShutdownTask.class)) {
               running = false;
               ((ShutdownTask) next).latch.countDown();
               itr.remove();
             }
           }
           eventProcessor.process(batch);
         } else {
           // just the one event, no need to iterate
           if (event.getClass().equals(ShutdownTask.class)) {
             running = false;
             ((ShutdownTask) event).latch.countDown();
           } else {
             eventProcessor.process(batch);
           }
         }
       } catch (InterruptedException e) {
         LOG.warn(
             String.format(
                 "Consumer on queue %s interrupted.", Thread.currentThread().getName()));
         // ignore
       } catch (Throwable exception) {
         LOG.error(
             String.format(
                 "exception on queue %s while executing events",
                 Thread.currentThread().getName()),
             exception);
       } finally {
         // reset the batch
         batch.clear();
       }
     }
   } catch (Throwable unexpectedThrowable) {
     // we observed some cases where trying to log the inner exception threw an error
     // don't use the logger here as that seems to be causing the problem in the first place
     System.err.println("Caught and unexpected Throwable while logging");
     System.err.println(
         "This problem happens when jar files change at runtime, JVM might be UNSTABLE");
     unexpectedThrowable.printStackTrace(System.err);
   }
 }
 /**
  * Exports the throughput times of all process instances in piList to a comma-seperated text-file.
  *
  * @param piList ArrayList: the process instances used
  * @param file File: the file to which the times are exported
  * @param divider long: the time divider used
  * @param sort String: the time sort used
  * @param fitOption int: the fit option used (how to deal with non-conformance)
  * @throws IOException
  */
 public void exportToFile(ArrayList piList, File file, long divider, String sort, int fitOption)
     throws IOException {
   Writer output = new BufferedWriter(new FileWriter(file));
   String line = "Log Trace,Throughput time (" + sort + ")\n";
   output.write(line);
   ListIterator lit = piList.listIterator();
   while (lit.hasNext()) {
     ExtendedLogTrace currentTrace = (ExtendedLogTrace) lit.next();
     try {
       double tp =
           (currentTrace.getEndDate().getTime() - currentTrace.getBeginDate().getTime())
               * 1.0
               / divider;
       if (fitOption == 0) {
         // times based on all traces
         line = currentTrace.getName() + "," + tp + "\n";
         // write line to the file
         output.write(line);
       }
       if (fitOption == 1
           && currentTrace.hasProperlyTerminated()
           && currentTrace.hasSuccessfullyExecuted()) {
         // times based on fitting traces only
         line = currentTrace.getName() + "," + tp + "\n";
         // write line to the file
         output.write(line);
       }
     } catch (NullPointerException npe) {
     }
   }
   // close the file
   output.close();
 }
예제 #6
0
  public wordCount(String s) {
    long startTime = System.currentTimeMillis();
    list = new ArrayList<Node>();
    try {
      in = new Scanner(src = new File(s));
      while (in.hasNext()) {
        String str = in.next();
        str = str.replaceAll("\\p{P}", "");
        str = str.replaceAll("\\s", "");

        if (!str.equals("")) {
          Node n = new Node(str, 1);
          if (!exists(n, list)) {
            list.add(n);
          }
        }
      }
      iter = list.listIterator();

      Node[] orderedNodes = toOrderedArray(list, iter);
      printList(orderedNodes);
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }

    long endTime = System.currentTimeMillis();
    System.out.println("\nRuntime: " + (((float) (endTime - startTime) / 1000) + "s"));
  }
 /**
  * Si la fonction {@link #denyExit} a &eacute;t&eacute; appel&eacute;e avant cette fonction, cette
  * derni&egrave;re renvoit une {@link SecurityException}.
  */
 public void checkExit(int status) {
   Iterator iter = exitListeners.listIterator();
   while (iter.hasNext()) {
     ((SystemExitListener) iter.next()).exiting();
   }
   if (!bCanExit) throw new SecurityException((new Integer(status)).toString());
 }
  public void comparationUndefinedExactHours() {
    Scanner keyboard = new Scanner(System.in);
    int option = 0;
    MyComparator myComparator = new MyComparator();

    exactHours = new ArrayList<ExactHour>();

    do {
      exactHour = new ExactHour(0, 0, 0);
      takeExactHour(exactHour);
      exactHours.add(exactHour);

      System.out.println("Introduce another hour? (Yes(1)/No(0)): ");
      option = keyboard.nextInt();
      keyboard.nextLine();
    } while (option != 0);

    Collections.sort(exactHours, myComparator);

    exactHoursIt = exactHours.listIterator();

    while (exactHoursIt.hasNext()) {
      System.out.println(exactHoursIt.next().toString());
    }
  }
예제 #9
0
  // prints a list of Strings at the specified page
  public void list(CommandSender sender, ArrayList<String> strings, int page) {
    int pages = (int) Math.ceil(strings.size() / 7F);
    if (page > pages || page < 1) {
      page = 1;
    }

    sender.sendMessage(
        color(
            "&7-------------- &f"
                + languageReader.get("Etc_Page")
                + " &6"
                + page
                + "&f/&6"
                + pages
                + " &7--------------"));

    ListIterator<String> iter = strings.listIterator((page - 1) * 7);

    for (int i = 0; i < 7; i++) {
      if (iter.hasNext()) {
        sender.sendMessage(color(iter.next()));
      } else {
        break;
      }
    }
  }
예제 #10
0
 public static void main(String args[]) {
   ArrayList<Integer> numList = new ArrayList<Integer>();
   for (int i = 1; i <= 5; i++) {
     numList.add(i);
   }
   System.out.println("Size of Array List is " + numList.size());
   System.out.println("List elements");
   ListIterator<Integer> li = numList.listIterator();
   for (; li.hasNext(); ) {
     Integer num = li.next();
     System.out.println(num);
   }
   System.out.println("List elements in reverse");
   for (; li.hasPrevious(); ) {
     Integer num = li.previous();
     System.out.println(num);
   }
   LinkedList<String> strList = new LinkedList<String>();
   strList.add("abc");
   strList.add("def");
   strList.add("abc");
   strList.add("ghi");
   System.out.println("Index of abc is: " + strList.indexOf("abc"));
   System.out.println("Size of Linked List is " + strList.size());
   strList.remove("abc");
   for (ListIterator<String> ls = strList.listIterator(); ls.hasNext(); ) {
     String str = ls.next();
     System.out.println(str);
   }
 }
예제 #11
0
  public static void main(String[] args) {
    Scanner teclado = new Scanner(System.in);
    String nombre, pregunta;
    boolean continuar = true;
    ArrayList<String> cadenaNombres = new ArrayList<String>();

    do {
      System.out.println("Introduce el nombre: ");
      nombre = teclado.next();
      cadenaNombres.add(nombre);

      do {
        System.out.println("¿Quiere insertar otro nombre?(n|s)");
        pregunta = teclado.next();
        if (pregunta.equals("n")) continuar = false;
        else if (pregunta.equals("s")) continuar = true;
      } while (!pregunta.equals("s") && !pregunta.equals("n"));

    } while (continuar);

    ListIterator<String> ite = cadenaNombres.listIterator();
    System.out.println("Orden introducidos: ");
    while (ite.hasNext()) {
      System.out.println(ite.next());
    }

    System.out.println();
    System.out.println("Contrario: ");
    while (ite.hasPrevious()) {
      System.out.println(ite.previous());
    }
  }
예제 #12
0
  /**
   * Send an event to all registered listeners, except the named one.
   *
   * @param event the event to be sent: public void method_name( event_class event)
   */
  public void sendEventExcludeSource(java.util.EventObject event) {
    if (!hasListeners) {
      return;
    }

    Object source = event.getSource();
    Object[] args = new Object[1];
    args[0] = event;

    // send event to all listeners except the source
    ListIterator iter = listeners.listIterator();
    while (iter.hasNext()) {
      Object client = iter.next();
      if (client == source) {
        continue;
      }

      try {
        method.invoke(client, args);
      } catch (IllegalAccessException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalAccessException = " + e);
      } catch (IllegalArgumentException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalArgumentException = " + e);
      } catch (InvocationTargetException e) {
        iter.remove();
        System.err.println("ListenerManager InvocationTargetException on " + method);
        System.err.println("   threw exception " + e.getTargetException());
        e.printStackTrace();
      }
    }
  }
예제 #13
0
  /**
   * Очистка и удаление директории текущего запроса. Удаляются только файлы связанные с выполнением
   * запроса. Если в директории остались другие файлы, временная директория удалена не будет.
   *
   * @param onExit - true для очистки и удалении по завершению работы JavaVM или false - для очистки
   *     и удалении немедленно.
   */
  public void clean(boolean onExit) {
    if (tmpRqstDir.exists()) {
      ListIterator<IOFile> iterator = null;

      // Удаляем intput файлы
      iterator = inputFiles.listIterator();
      while (iterator.hasNext())
        if (onExit) iterator.next().deleteOnExit();
        else iterator.next().delete();

      // Удаляем output файлы
      iterator = outputFiles.listIterator();
      while (iterator.hasNext())
        if (onExit) iterator.next().deleteOnExit();
        else iterator.next().delete();
    }
  }
예제 #14
0
파일: World.java 프로젝트: munro/lzr
 public void render() {
   ListIterator<Wall> it;
   Wall w;
   for (it = walls.listIterator(); it.hasNext(); ) {
     w = it.next();
     w.render();
   }
 }
 @Override
 public ListIterator<ServiceReference> listIterator(int arg0) {
   if (serviceSet != null) {
     ArrayList<ServiceReference> list = new ArrayList<ServiceReference>(serviceSet);
     return list.listIterator(arg0);
   }
   return null;
 }
예제 #16
0
 public void setList(ArrayList<String> element_path) {
   element.clear();
   ListIterator<String> listIterator = element_path.listIterator();
   while (listIterator.hasNext()) {
     element.add(listIterator.next());
   }
   number_element = element.size();
 }
예제 #17
0
 public void reloadStyles() {
   ListIterator<SectionRecord> k = records.listIterator();
   while (k.hasNext()) {
     SectionRecord record = k.next();
     k.remove();
     k.add(new SectionRecord(record.getStyleName(), record.getIndex(), record.getIsPhrase()));
   }
 }
예제 #18
0
 /**
  * transpose / 1 Takes a brick and transposes all of its elements up by the difference specified
  *
  * @param diff, a long indicating semitones ascending difference
  */
 @Override
 public void transpose(long diff) {
   key = (key + diff + 12) % 12;
   ListIterator<Block> iter = subBlocks.listIterator();
   while (iter.hasNext()) {
     Block block = iter.next();
     block.transpose(diff);
   }
 }
예제 #19
0
 static ListIterator<XSObject> listIteratorFromXSObjectList(XSObjectList list) {
   ArrayList<XSObject> objects = new ArrayList<XSObject>(list.getLength());
   for (int i = 0; i < list.getLength(); i++) {
     if (list.item(i) != null) {
       objects.add(list.item(i));
     }
   }
   return objects.listIterator();
 }
예제 #20
0
 /**
  * Returns an iterator of all parameter names of the paramters in the list. Returns the list in
  * the order the elements were added.
  */
 public ListIterator<String> getParameterNamesIterator() {
   ArrayList<String> v = new ArrayList<String>();
   int size = this.params.size();
   for (int i = 0; i < size; ++i) {
     ParameterAPI obj = (ParameterAPI) params.get(i);
     v.add(obj.getName());
   }
   return v.listIterator();
 }
예제 #21
0
  /**
   * Поиск файла в списке intput/output файлов модуля по имени.
   *
   * @param fileName - имя файла.
   * @param io - тип файла (intput/output).
   * @return наденный IOFile или null, если не найден.
   */
  private IOFile search(String fileName, TypeIOFile io) {
    ListIterator<IOFile> iter = null;

    // В соответствии типу файла:
    if (TypeIOFile.INPUT == io) {
      iter = inputFiles.listIterator();
    } else {
      iter = outputFiles.listIterator();
    }

    while (iter.hasNext()) {
      IOFile curFile = iter.next();
      if (curFile.getName().equals(fileName)) {
        return curFile;
      }
    }
    return null;
  }
예제 #22
0
  public void printAllAutomobile() {

    ListIterator<Automobile> it1 = vehlist.listIterator();
    while (it1.hasNext()) {
      Automobile t = it1.next();
      System.out.println(
          "type:" + t.getClass().getName() + ",engine:" + t.getEngineCc() + ", age:" + t.getAge());
    }
  }
  public String generatePieChart(
      String hitOrdNum, HttpSession session, PrintWriter pw, String courseId, int studentId) {
    /* int groupId=0;
                if (groupName.equals("All")){
                    groupId=0;
                }else{
                     groupId = studStatisticBean.getGroupIdByName(groupName);
    }*/
    String filename = null;
    try {
      //  Retrieve list of WebHits
      StudentsConceptChartDataSet whDataSet =
          new StudentsConceptChartDataSet(studStatisticBean, courseId, studentId);
      ArrayList list = whDataSet.getDataBySection(hitOrdNum);

      //  Throw a custom NoDataException if there is no data
      if (list.size() == 0) {
        System.out.println("No data has been found");
        throw new NoDataException();
      }

      //  Create and populate a PieDataSet
      DefaultPieDataset data = new DefaultPieDataset();
      Iterator iter = list.listIterator();
      while (iter.hasNext()) {
        StudentsConceptHit wh = (StudentsConceptHit) iter.next();
        data.setValue(wh.getSection(), wh.getHitDegree());
      }

      //  Create the chart object
      PiePlot plot = new PiePlot(data);
      plot.setInsets(new Insets(0, 5, 5, 5));
      plot.setURLGenerator(new StandardPieURLGenerator("xy_chart.jsp", "section"));
      plot.setToolTipGenerator(new StandardPieItemLabelGenerator());
      JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
      chart.setBackgroundPaint(java.awt.Color.white);

      //  Write the chart image to the temporary directory
      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, info, session);

      //  Write the image map to the PrintWriter
      ChartUtilities.writeImageMap(pw, filename, info);
      pw.flush();

    } catch (NoDataException e) {
      System.out.println(e.toString());
      filename = "public_nodata_500x300.png";
    } catch (Exception e) {
      System.out.println("Exception - " + e.toString());
      e.printStackTrace(System.out);
      filename = "public_error_500x300.png";
    }

    return filename;
  }
예제 #24
0
  /**
   * Outputs filled with points listOfPointsToBeConnected. Finds the point with the lowest Y - that
   * will be the first point of the broken line. If It finds several points with equal Ys - makes a
   * line from the most left (lowest X) point to the most right point, then connects this point with
   * next point with the lowest Y from the remaining set. The last point of the broken line will be
   * the point with the highest Y, or if there will be several points with the highest Y - the point
   * with the highest X from this set.
   */
  void connectPoints() {

    ArrayList<MyPoint> pointsInOneRow =
        new ArrayList<MyPoint>(); // will store points with equal Ys.
    MyPoint currentPoint, nextPoint;
    ListIterator<MyPoint> itr;

    while (randomListOfPoints.size() > 0) {

      pointsInOneRow.clear(); // clear the pointsInOneRow.
      itr = randomListOfPoints.listIterator();
      // initialize list iterator and place it before the first element in the randomListOfPoints.
      currentPoint = itr.next(); // the first element from the randomListOfPoints.
      itr.remove(); // delete the first element from the randomListOfPoints.
      if (itr.hasNext()) { // if it's not the end of the randomListOfPoints.

        nextPoint = itr.next(); // the second element from the randomListOfPoints.

      } else {

        // the point not from the range of possible Xs and Ys, so we can be sure that its' Y won't
        // be equal to the currentPoints'.
        nextPoint = new MyPoint(-1, -1);
      }
      pointsInOneRow.add(
          currentPoint); // add current point to a list of points, that lies on one line.
      // if the currentPoint and the nextPoint are on the same line, that is parallel to the X axis.
      while (currentPoint.getY() == nextPoint.getY()) {

        pointsInOneRow.add(
            nextPoint); // add the nextPoint to a list of points, that lies on one line.
        itr.remove(); // delete the second element from the randomListOfPoints .
        currentPoint = nextPoint; // the currentPoint equals to the nextPoint now.
        if (itr.hasNext()) { // if it's not the end of the randomListOfPoints.

          nextPoint = itr.next(); // the second element from the randomListOfPoints.

        } else {

          // the point not from the range of possible Xs and Ys, so we can be sure that its' Y won't
          // be equal to the currentPoints'.
          nextPoint = new MyPoint(-1, -1);
        }
      }

      Collections.sort(
          pointsInOneRow, new XcoordSorterComparator()); // sort the pointsInOneRow by X
      /* add all elements from the pointsInOneRow to the end of the listOfPointsToBeConnected.
       * If the listOfPointsToBeConnected.size == 0 - the first element from the pointsInOneRow will be the start
       * of the broken line, if the listOfPointsToBeConnected.size != 0 - the first element from the
       * pointsInOneRow will be connected with the last element from the listOfPointsToBeConnected*/
      listOfPointsToBeConnected.addAll(listOfPointsToBeConnected.size(), pointsInOneRow);
    }

    System.out.println("\n\nList of connected points:\n" + listOfPointsToBeConnected);
  }
예제 #25
0
 public void removeAllPets() {
   Iterator<LivingPet> i = pets.listIterator();
   while (i.hasNext()) {
     LivingPet p = i.next();
     saveFileData("autosave", p);
     ec.SPH.saveToDatabase(p, false);
     p.removePet();
     i.remove();
   }
 }
예제 #26
0
 public Integer getNextSectionIndex(int n) {
   ListIterator<SectionRecord> k = records.listIterator();
   while (k.hasNext()) {
     int index = k.next().getIndex();
     if (index > n) {
       return index;
     }
   }
   return null;
 }
예제 #27
0
파일: World.java 프로젝트: munro/lzr
 boolean intersectsWall(Vector2f a, Vector2f b) {
   ListIterator<Wall> it;
   Wall w;
   // int x = 0;
   for (it = walls.listIterator(); it.hasNext(); ) {
     w = it.next();
     // System.out.println("HEY " + (x++));
     if (w.intersectsLine(a, b)) return true;
   }
   return false;
 }
예제 #28
0
 public void removePets(Player player) {
   Iterator<LivingPet> i = pets.listIterator();
   while (i.hasNext()) {
     LivingPet p = i.next();
     if (p.getOwner().getName().equals(player.getName())) {
       /*saveFileData("autosave", p);
       ec.SPH.saveToDatabase(p, false);*/
       p.removePet();
       i.remove();
     }
   }
 }
예제 #29
0
 public void setValue(Object newSet) {
   if (newSet instanceof ArrayList) { // convert to set
     ArrayList newList = (ArrayList) newSet;
     Set anotherSet = new HashSet();
     for (ListIterator i = newList.listIterator(); i.hasNext(); ) {
       anotherSet.add(i.next());
     }
     this.set = anotherSet;
   } else {
     this.set = (Set) newSet;
   }
 }
예제 #30
0
  public static void main(String[] args) {

    // 演示列表迭代器。
    ArrayList al = new ArrayList();

    // 添加元素
    al.add("java01");
    al.add("java02");
    al.add("java03");

    sop(al);

    ListIterator li = al.listIterator();

    // sop("hasPrevious():"+li.hasPrevious());

    while (li.hasNext()) {
      Object obj = li.next();

      if (obj.equals("java02"))
        // li.add("java009");
        li.set("java006");
    }

    while (li.hasPrevious()) {
      sop("pre::" + li.previous());
    }
    // sop("hasNext():"+li.hasNext());
    // sop("hasPrevious():"+li.hasPrevious());

    sop(al);

    /*
    //在迭代过程中,准备添加或者删除元素。

    Iterator it = al.iterator();

    while(it.hasNext())
    {
    	Object obj = it.next();

    	if(obj.equals("java02"))
    		//al.add("java008");
    		it.remove();//将java02的引用从集合中删除了。

    	sop("obj="+obj);


    }
    sop(al);
    */

  }