Example usage for java.util ArrayList add

List of usage examples for java.util ArrayList add

Introduction

In this page you can find the example usage for java.util ArrayList add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:com.google.appengine.tools.pipeline.impl.util.JsonUtils.java

public static void main(String[] args) throws Exception {
    JSONObject x = new JSONObject();
    x.put("first", 5);
    x.put("second", 7);
    debugPrint("hello");
    debugPrint(7);//from  w ww . j  av  a 2 s .  co  m
    debugPrint(3.14159);
    debugPrint("");
    debugPrint('x');
    debugPrint(x);
    debugPrint(null);

    Map<String, Integer> map = new HashMap<>();
    map.put("first", 5);
    map.put("second", 7);
    debugPrint(map);

    int[] array = new int[] { 5, 7 };
    debugPrint(array);

    ArrayList<Integer> arrayList = new ArrayList<>(2);
    arrayList.add(5);
    arrayList.add(7);
    debugPrint(arrayList);

    Collection<Integer> collection = new HashSet<>(2);
    collection.add(5);
    collection.add(7);
    debugPrint(collection);

    Object object = new Object();
    debugPrint(object);

    Map<String, String> map1 = new HashMap<>();
    map1.put("a", "hello");
    map1.put("b", "goodbye");

    Object[] array2 = new Object[] { 17, "yes", "no", map1 };

    Map<String, Object> map2 = new HashMap<>();
    map2.put("first", 5.4);
    map2.put("second", array2);
    map2.put("third", map1);

    debugPrint(map2);

    class MyBean {
        @SuppressWarnings("unused")
        public int getX() {
            return 11;
        }

        @SuppressWarnings("unused")
        public boolean isHot() {
            return true;
        }

        @SuppressWarnings("unused")
        public String getName() {
            return "yellow";
        }
    }
    debugPrint(new MyBean());

}

From source file:de.prozesskraft.pkraft.Checkconsistency.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*from  ww w .  j  av a 2  s .co m*/
    ----------------------------*/
    File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Checkconsistency.class) + "/"
            + "../etc/pkraft-checkconsistency.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option odefinition = OptionBuilder.withArgName("definition").hasArg()
            .withDescription("[mandatory] process model in xml format.")
            //            .isRequired()
            .create("definition");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(odefinition);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("startinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.out.println("option -definition is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process p1 = new Process();

    p1.setInfilexml(commandline.getOptionValue("definition"));
    Process p2;
    try {
        p2 = p1.readXml();

        if (p2.isProcessConsistent()) {
            System.out.println("process structure is consistent.");
        } else {
            System.out.println("process structure is NOT consistent.");
        }

        p2.printLog();

    } catch (JAXBException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:org.jfree.chart.demo.ImageMapDemo3.java

/**
 * Starting point for the demo./*from ww  w  .  j  a  v a2 s  .  co m*/
 *
 * @param args  ignored.
 *
 * @throws ParseException if there is a problem parsing dates.
 */
public static void main(final String[] args) throws ParseException {

    //  Create a sample dataset
    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    final XYSeries dataSeries = new XYSeries("Curve data");
    final ArrayList toolTips = new ArrayList();
    dataSeries.add(sdf.parse("01-Jul-2002").getTime(), 5.22);
    toolTips.add("1D - 5.22");
    dataSeries.add(sdf.parse("02-Jul-2002").getTime(), 5.18);
    toolTips.add("2D - 5.18");
    dataSeries.add(sdf.parse("03-Jul-2002").getTime(), 5.23);
    toolTips.add("3D - 5.23");
    dataSeries.add(sdf.parse("04-Jul-2002").getTime(), 5.15);
    toolTips.add("4D - 5.15");
    dataSeries.add(sdf.parse("05-Jul-2002").getTime(), 5.22);
    toolTips.add("5D - 5.22");
    dataSeries.add(sdf.parse("06-Jul-2002").getTime(), 5.25);
    toolTips.add("6D - 5.25");
    dataSeries.add(sdf.parse("07-Jul-2002").getTime(), 5.31);
    toolTips.add("7D - 5.31");
    dataSeries.add(sdf.parse("08-Jul-2002").getTime(), 5.36);
    toolTips.add("8D - 5.36");
    final XYSeriesCollection xyDataset = new XYSeriesCollection(dataSeries);
    final CustomXYToolTipGenerator ttg = new CustomXYToolTipGenerator();
    ttg.addToolTipSeries(toolTips);

    //  Create the chart
    final StandardXYURLGenerator urlg = new StandardXYURLGenerator("xy_details.jsp");
    final ValueAxis timeAxis = new DateAxis("");
    final NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false); // override default
    final XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, null);
    final StandardXYItemRenderer sxyir = new StandardXYItemRenderer(
            StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES, ttg, urlg);
    sxyir.setShapesFilled(true);
    plot.setRenderer(sxyir);
    final JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("xychart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("xychart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"xychart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }
    return;
}

From source file:edu.oregonstate.eecs.mcplan.ml.KMeans.java

/**
 * @param args//from w w  w . j a va2 s . c  o  m
 */
public static void main(final String[] args) {
    final int nclusters = 2;
    final ArrayList<RealVector> data = new ArrayList<RealVector>();

    for (int x = -1; x <= 1; ++x) {
        for (int y = -1; y <= 1; ++y) {
            data.add(new ArrayRealVector(new double[] { x, y }));
            data.add(new ArrayRealVector(new double[] { x + 10, y + 10 }));
        }
    }

    final KMeans kmeans = new KMeans(nclusters, data.toArray(new RealVector[data.size()])); /* {
                                                                                            @Override
                                                                                            public double distance( final RealVector a, final RealVector b ) {
                                                                                            return a.getL1Distance( b );
                                                                                            }
                                                                                            };
                                                                                            */

    kmeans.run();
    for (int i = 0; i < kmeans.centers().length; ++i) {
        System.out.println("Center " + i + ": " + kmeans.centers()[i]);
        for (int j = 0; j < kmeans.clusters().length; ++j) {
            if (kmeans.clusters()[j] == i) {
                System.out.println("\tPoint " + data.get(j));
            }
        }
    }

}

From source file:SortByHouseNo.java

public static void main(String[] args) {
    String houseList[] = { "9-11", "9-01", "10-02", "10-01", "2-09", "3-88", "9-03", "9-3" };
    HouseNo house = null;/*from   w w w  .ja  v  a2s  .  c  om*/
    ArrayList<HouseNo> sortedList = new ArrayList<>();
    for (String string : houseList) {
        String h = string.substring(0, string.indexOf('-'));
        String b = string.substring(string.indexOf('-') + 1);
        house = new HouseNo(h, b);
        sortedList.add(house);
    }

    System.out.println("Before Sorting :: ");
    for (HouseNo houseNo : sortedList) {
        System.out.println(houseNo);
    }

    Collections.sort(sortedList, new SortByHouseNo());
    System.out.println("\n\nAfter Sorting HouseNo :: ");
    for (HouseNo houseNo : sortedList) {
        System.out.println(houseNo);
    }
}

From source file:com.l2jfree.tools.ProjectSettingsSynchronizer.java

public static void main(String[] args) throws IOException {
    final File src = new File(".").getCanonicalFile();
    System.out.println("Copying from: " + src);
    System.out.println();//ww  w .j  a va2 s. c  o  m

    final List<File> destinations = new ArrayList<File>();
    for (File dest : src.getParentFile().listFiles()) {
        if (dest.isHidden() || !dest.isDirectory())
            continue;

        destinations.add(dest);
        System.out.println("Copying to: " + dest);
    }
    System.out.println();

    // .project
    System.out.println(".project");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".project"));

        for (File dest : destinations) {
            lines.set(2, lines.get(2).replaceAll(src.getName(), dest.getName()));
            writeLines(dest, ".project", lines);
            lines.set(2, lines.get(2).replaceAll(dest.getName(), src.getName()));
        }
    }
    System.out.println();

    // .classpath
    System.out.println(".classpath");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".classpath"));

        for (File dest : destinations) {
            if (dest.getName().endsWith("-main") || dest.getName().endsWith("-datapack")) {
                final ArrayList<String> tmp = new ArrayList<String>();

                for (String line : lines)
                    if (!line.contains("classpathentry"))
                        tmp.add(line);

                writeLines(dest, ".classpath", tmp);
                continue;
            }

            writeLines(dest, ".classpath", lines);
        }
    }
    System.out.println();

    // .settings
    System.out.println(".settings");
    System.out.println("================================================================================");
    for (File settingsFile : new File(src, ".settings").listFiles()) {
        if (settingsFile.getName().endsWith(".prefs")) {
            System.out.println(".settings/" + settingsFile.getName());
            System.out.println(
                    "--------------------------------------------------------------------------------");

            final List<String> lines = FileUtils.readLines(settingsFile);

            if (lines.get(0).startsWith("#"))
                lines.remove(0);

            for (File dest : destinations) {
                writeLines(new File(dest, ".settings"), settingsFile.getName(), lines);
            }
            System.out.println();
        }
    }
    System.out.println();
}

From source file:edu.oregonstate.eecs.mcplan.domains.taxi.TaxiMDP.java

public static void main(final String[] argv) {
    final int Nother_taxis = 2;
    final double slip = 0.1;
    final double discount = 0.9;
    final RandomGenerator rng = new MersenneTwister(42);
    final TaxiState template = TaxiWorlds.dietterich2000(rng, Nother_taxis, slip);
    final TaxiMDP mdp = new TaxiMDP(template);
    final int Nfeatures = new PrimitiveTaxiRepresentation(template).phi().length;
    final SparseValueIterationSolver<TaxiState, TaxiAction> vi = new SparseValueIterationSolver<TaxiState, TaxiAction>(
            mdp, discount);/* w w  w.jav a  2s.co  m*/
    vi.run();

    final PrimitiveTaxiRepresenter repr = new PrimitiveTaxiRepresenter(template);
    final ArrayList<Attribute> attr = new ArrayList<Attribute>();
    attr.addAll(repr.attributes());
    attr.add(WekaUtil.createNominalAttribute("__label__", mdp.A().cardinality()));
    final Instances instances = WekaUtil.createEmptyInstances("taxi_" + Nother_taxis + "_pistar", attr);
    final Policy<TaxiState, TaxiAction> pistar = vi.pistar();
    final Generator<TaxiState> g = mdp.S().generator();
    while (g.hasNext()) {
        final TaxiState s = g.next();
        pistar.setState(s, 0L);
        final TaxiAction astar = pistar.getAction();
        final double[] phi = new double[Nfeatures + 1];
        Fn.memcpy_as_double(phi, new PrimitiveTaxiRepresentation(s).phi(), Nfeatures);
        phi[Nfeatures] = mdp.A().index(astar);
        WekaUtil.addInstance(instances, new DenseInstance(1.0, phi));
    }

    WekaUtil.writeDataset(new File("."), instances);
}

From source file:com.blogspot.devsk.l2j.geoconv.GeoGonv.java

public static void main(String[] args) {

    if (args == null || args.length == 0) {
        System.out.println("File name was not specified, [\\d]{1,2}_[\\d]{1,2}.txt will be used");
        args = new String[] { "[\\d]{1,2}_[\\d]{1,2}.txt" };
    }/*  w  w  w  . j  a v  a  2 s.  co  m*/

    File dir = new File(".");
    File[] files = dir.listFiles((FileFilter) new RegexFileFilter(args[0]));

    ArrayList<File> checked = new ArrayList<File>();
    for (File file : files) {
        if (file.isDirectory() || file.isHidden() || !file.exists()) {
            System.out.println(file.getAbsoluteFile() + " was ignored.");
        } else {
            checked.add(file);
        }
    }

    if (OUT_DIR.exists() && OUT_DIR.isDirectory() && OUT_DIR.listFiles().length > 0) {
        try {
            System.out.println("Directory with generated files allready exists, making backup...");
            FileUtils.moveDirectory(OUT_DIR, new File("generated-backup-" + System.currentTimeMillis()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (!OUT_DIR.exists()) {
        OUT_DIR.mkdir();
    }

    for (File file : checked) {
        GeoConvThreadFactory.startThread(new ParseTask(file));
    }
}

From source file:com.handany.base.generator.Generator.java

public static void main(String[] args) throws IOException {
    String directoryPath = "src/main/java";

    String modelDirectory = directoryPath + File.separator
            + StringUtils.replace(MODEL_PACKAGE, ".", File.separator) + File.separator;
    String daoDirectory = directoryPath + File.separator + StringUtils.replace(DAO_PACKAGE, ".", File.separator)
            + File.separator;/* w ww .j  av a2  s .  co  m*/
    String serviceDirectory = directoryPath + File.separator
            + StringUtils.replace(SERVICE_PACKAGE, ".", File.separator) + File.separator;
    String serviceImplDirectory = directoryPath + File.separator
            + StringUtils.replace(SERVICE_IMPL_PACKAGE, ".", File.separator) + File.separator;
    String controllerDirectory = directoryPath + File.separator
            + StringUtils.replace(CONTROLLER_PACKAGE, ".", File.separator) + File.separator;
    File fileDirectory = new File(directoryPath);
    if (!fileDirectory.isDirectory()) {
        FileUtils.forceMkdir(fileDirectory);
    }

    List<TableBean> tableBeanList = getTables();

    ArrayList<String> nameList = new ArrayList<>();

    //      nameList.add("bm_classroom_course");
    nameList.add("bm_sales_promotion");

    for (TableBean tableBean : tableBeanList) {
        System.out.println("table:" + tableBean.getTableName());
        String tableName = tableBean.getTableName();

        if (!nameList.contains(tableName.toLowerCase())) {
            continue;
        }

        Map<String, Object> varMap = new HashMap<>();
        varMap.put("tableBean", tableBean);
        varMap.put("schemaName", SCHEMA_NAME);
        varMap.put("modelPackage", MODEL_PACKAGE);
        varMap.put("daoPackage", DAO_PACKAGE);
        varMap.put("servicePackage", SERVICE_PACKAGE);
        varMap.put("serviceImplPackage", SERVICE_IMPL_PACKAGE);
        varMap.put("controllerPackage", CONTROLLER_PACKAGE);

        Template modelTemplate = FreemarkerUtil.getTemplate("model.ftl");
        FreemarkerUtil.outputProcessResult(modelDirectory + tableBean.getTableNameCapitalized() + ".java",
                modelTemplate, varMap);

        //            Template daoTemplate = FreemarkerUtil.getTemplate("dao.ftl");
        //            FreemarkerUtil.outputProcessResult(daoDirectory + tableBean.getTableNameCapitalized() + "Mapper.java", daoTemplate, varMap);

        Template mapperTemplate = FreemarkerUtil.getTemplate("mapper.ftl");
        FreemarkerUtil.outputProcessResult(daoDirectory + tableBean.getTableNameCapitalized() + "Mapper.xml",
                mapperTemplate, varMap);

        //            Template serviceTemplate = FreemarkerUtil.getTemplate("service.ftl");
        //            FreemarkerUtil.outputProcessResult(serviceDirectory + tableBean.getTableNameCapitalized() + "Service.java", serviceTemplate, varMap);
        //
        //            Template serviceImplTemplate = FreemarkerUtil.getTemplate("serviceimpl.ftl");
        //            FreemarkerUtil.outputProcessResult(serviceImplDirectory + tableBean.getTableNameCapitalized() + "ServiceImpl.java", serviceImplTemplate, varMap);
        //
        //            Template controllerTemplate = FreemarkerUtil.getTemplate("controller.ftl");
        //            FreemarkerUtil.outputProcessResult(controllerDirectory + tableBean.getTableNameCapitalized() + "Controller.java", controllerTemplate, varMap);
    }
}

From source file:mujava.cli.testnew.java

public static void main(String[] args) throws IOException {
    testnewCom jct = new testnewCom();
    String[] argv = { "Flower", "/Users/dmark/mujava/src/Flower" };
    new JCommander(jct, args);

    muJavaHomePath = Util.loadConfig();
    // muJavaHomePath= "/Users/dmark/mujava";

    // check if debug mode
    if (jct.isDebug() || jct.isDebugMode()) {
        Util.debug = true;//  w ww . j  a  v  a  2  s .  c o m
    }
    System.out.println(jct.getParameters().size());
    sessionName = jct.getParameters().get(0); // set first parameter as the
    // session name

    ArrayList<String> srcFiles = new ArrayList<>();

    for (int i = 1; i < jct.getParameters().size(); i++) {
        srcFiles.add(jct.getParameters().get(i)); // retrieve all src file
        // names from parameters
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if the session is new or not
    if (fileNameList.contains(sessionName)) {
        Util.Error("Session already exists.");
    } else {
        // create sub-directory for the session
        setupSessionDirectory(sessionName);

        // move src files into session folder
        for (String srcFile : srcFiles) {
            // new (dir, name)
            // check abs path or not

            // need to check if srcFile has .java at the end or not
            if (srcFile.length() > 5) {
                if (srcFile.substring(srcFile.length() - 5).equals(".java")) // name has .java at the end, e.g. cal.java
                {
                    // delete .java, e.g. make it cal
                    srcFile = srcFile.substring(0, srcFile.length() - 5);
                }
            }

            File source = new File(srcFile + ".java");

            if (!source.isAbsolute()) // relative path, attach path, e.g. cal.java, make it c:\mujava\cal.java
            {
                source = new File(muJavaHomePath + "/src" + java.io.File.separator + srcFile + ".java");

            }

            File desc = new File(muJavaHomePath + "/" + sessionName + "/src");
            FileUtils.copyFileToDirectory(source, desc);

            // compile src files
            // String srcName = "t";
            boolean result = compileSrc(srcFile);
            if (result)
                Util.Print("Session is built successfully.");
        }

    }

    // System.exit(0);
}