Example usage for java.util ArrayList toArray

List of usage examples for java.util ArrayList toArray

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

From source file:com.jaspersoft.jasperserver.export.util.CommandUtils.java

protected static String[] breakParms(String[] args) {

    ArrayList list = new ArrayList();

    for (int i = 0; i < args.length; i++) {

        int first = args[i].indexOf(ARG_PREFIX);
        int last = args[i].lastIndexOf(ARG_PREFIX);

        if (first < last) {
            // param string has more than one ARG_PREFIX so break it up
            for (StringTokenizer tok = new StringTokenizer(args[i]); tok.hasMoreTokens();) {
                String token = tok.nextToken();
                list.add((String) token);
            }//w  w w .j a  va  2  s .  com
        } else if (first == last) {
            list.add((String) args[i]);
        } else {
            log.error("ERROR: an argument string should always have an ARG_PREFIX (--) arg=" + args[i]);
        }
    }
    return (String[]) list.toArray(new String[list.size()]);
}

From source file:mase.neat.NEATSerializer.java

public static double[] serializeToArray(NEATNeuralNet net) {
    NEATNetDescriptor descr = (NEATNetDescriptor) net.netDescriptor();
    NEATChromosome chromo = (NEATChromosome) descr.neatStructure();
    Gene[] genes = chromo.genes();/*from ww  w  .  j  ava 2  s .com*/
    ArrayList<Double> res = new ArrayList<Double>();
    for (Gene gene : genes) {
        if (gene instanceof NEATNodeGene) {
            NEATNodeGene neatGene = (NEATNodeGene) gene;
            res.add(NODE);
            res.add((double) neatGene.id());
            res.add(neatGene.sigmoidFactor());
            res.add((double) neatGene.getType());
            res.add(neatGene.bias());
        } else if (gene instanceof NEATLinkGene) {
            NEATLinkGene neatGene = (NEATLinkGene) gene;
            res.add(LINK);
            res.add(neatGene.isEnabled() ? 1d : 0d);
            res.add((double) neatGene.getFromId());
            res.add((double) neatGene.getToId());
            res.add(neatGene.getWeight());
        }
    }
    Double[] array = new Double[res.size()];
    res.toArray(array);
    return ArrayUtils.toPrimitive(array);
}

From source file:com.linkedin.urls.detection.CharUtils.java

/**
 * Splits a string without the use of a regex, which could split either by isDot() or %2e
 * @param input the input string that will be split by dot
 * @return an array of strings that is a partition of the original string split by dot
 *///ww w.ja v a2s  .  co  m
public static String[] splitByDot(String input) {
    ArrayList<String> splitList = new ArrayList<String>();
    StringBuilder section = new StringBuilder();
    if (StringUtils.isEmpty(input)) {
        return new String[] { "" };
    }
    InputTextReader reader = new InputTextReader(input);
    while (!reader.eof()) {
        char curr = reader.read();
        if (isDot(curr)) {
            splitList.add(section.toString());
            section.setLength(0);
        } else if (curr == '%' && reader.canReadChars(2) && reader.peek(2).equalsIgnoreCase("2e")) {
            reader.read();
            reader.read(); //advance past the 2e
            splitList.add(section.toString());
            section.setLength(0);
        } else {
            section.append(curr);
        }
    }
    splitList.add(section.toString());
    return splitList.toArray(new String[splitList.size()]);
}

From source file:org.uimafit.factory.TypeSystemDescriptionFactory.java

/**
 * Scan patterns from manifest files and from the specified system property.
 *
 * @param manifestPatterns pattern matching the manifest files.
 * @param importProperty system property containing additional patterns.
 * @return array or all patterns found.// w w  w  .j a v a  2 s .c o m
 */
public static String[] scanImportsAndManifests(String manifestPatterns, String importProperty)
        throws ResourceInitializationException {
    ArrayList<String> patterns = new ArrayList<String>();

    // Scan auto-import locations
    patterns.addAll(Arrays.asList(System.getProperty(importProperty, "").split(";")));

    // Scan manifest
    for (String mfUrl : resolve(manifestPatterns)) {
        InputStream is = null;
        try {
            is = new URL(mfUrl).openStream();
            @SuppressWarnings("unchecked")
            List<? extends String> lines = IOUtils.readLines(is);
            patterns.addAll(lines);
        } catch (IOException e) {
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    return patterns.toArray(new String[patterns.size()]);
}

From source file:Main.java

/**
 * return a 2d array with the value and its count. Can deal with multiples.
 * Values will be in the same order as array (with subsequent duplicate
 * values removed). *//from   www. j a v a2s.c  om
 * 
 * @param array
 *            the array
 * @param verbose
 *            the verbose
 * @return the count
 */
public static String[][] getCount(String[] array, boolean verbose) {
    ArrayList<String[]> countArray = new ArrayList<String[]>();
    double count = 0;
    for (int i = 0; i < array.length; ++i) {
        // check if list contains current value
        boolean unique = true;
        for (String[] ia : countArray) {
            if (ia[0].equals(array[i])) {
                unique = false;
            }
        }
        // Count values
        if (unique) {
            count = 1;
            for (int j = i + 1; j < array.length; ++j) {
                if (array[i] == array[j]) {
                    count++;
                }
            }
            countArray.add(new String[] { array[i], String.valueOf(count) });
        }
    }
    // Log.d(countArray);
    String[][] stringArray = new String[countArray.size()][];
    stringArray = countArray.toArray(stringArray);
    if (verbose) {
        System.out.println("Value and count of value:\n" + Arrays.deepToString(stringArray));
    }
    return stringArray;
}

From source file:com.esri.core.geometry.GeometryEngine.java

/**
 * Calculates a buffer polygon for each geometry at each of the 
 * corresponding specified distances.  It is assumed that all geometries have
 * the same spatial reference. There is an option to union the 
 * returned geometries.//from  ww  w  .  ja  v a 2s. c o  m
 * @param geometries An array of geometries to be buffered.
 * @param spatialReference The spatial reference of the geometries.
 * @param distances The corresponding distances for the input geometries to be buffered.
 * @param toUnionResults TRUE if all geometries buffered at a given distance are to be unioned into a single polygon.
 * @return The buffer of the geometries.
 * */
public static Polygon[] buffer(Geometry[] geometries, SpatialReference spatialReference, double[] distances,
        boolean toUnionResults) {
    // initially assume distances are in unit of spatial reference
    double[] bufferDistances = distances;

    OperatorBuffer op = (OperatorBuffer) factory.getOperator(Operator.Type.Buffer);

    if (toUnionResults) {
        SimpleGeometryCursor inputGeometriesCursor = new SimpleGeometryCursor(geometries);
        GeometryCursor result = op.execute(inputGeometriesCursor, spatialReference, bufferDistances,
                toUnionResults, null);

        ArrayList<Polygon> resultGeoms = new ArrayList<Polygon>();
        Geometry g;
        while ((g = result.next()) != null) {
            resultGeoms.add((Polygon) g);
        }
        Polygon[] buffers = resultGeoms.toArray(new Polygon[0]);
        return buffers;
    } else {
        Polygon[] buffers = new Polygon[geometries.length];
        for (int i = 0; i < geometries.length; i++) {
            buffers[i] = (Polygon) op.execute(geometries[i], spatialReference, bufferDistances[i], null);
        }
        return buffers;
    }
}

From source file:net.giovannicapuano.galax.controller.User.java

/**
 * Fetch the messages sent to the given user.
 *///from  w  ww.  ja  va  2  s . c  o  m
public static Message[] fetchMessages(User user, Context context) throws Exception {
    String body = Utils.get("/user/messages/" + Uri.encode(user.getUsername()), context).getBody();
    ArrayList<Message> messages = new ArrayList<Message>();

    try {
        if (body.startsWith("{")) {
            int status = new JSONObject(body).getInt("status");
            throw new Exception("Error status: " + status);
        }
        JSONArray jsonArray = new JSONArray(body);
        for (int i = 0, len = jsonArray.length(); i < len; ++i) {
            JSONObject json = jsonArray.getJSONObject(i);
            messages.add(new Message(json.getInt("id"), json.getString("from"), json.getString("to"),
                    json.getString("text")));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return messages.toArray(new Message[0]);
}

From source file:StringUtilities.java

public static String[] segment(String source, int maxSegmentSize) {
    ArrayList<String> tmp = new ArrayList<String>();
    if (source.length() <= maxSegmentSize) {
        return new String[] { source };
    }/*  www  . j ava  2  s  . com*/
    boolean done = false;
    int currBeginIdx = 0;
    int currEndIdx = maxSegmentSize;
    while (!done) {
        String segment = source.substring(currBeginIdx, currEndIdx);
        tmp.add(segment);
        if (currEndIdx >= source.length()) {
            done = true;
            continue;
        }
        currBeginIdx = currEndIdx;
        currEndIdx += maxSegmentSize;
        if (currEndIdx > source.length()) {
            currEndIdx = source.length();
        }
    }
    return tmp.toArray(new String[tmp.size()]);
}

From source file:gov.vha.isaac.ochre.api.LookupService.java

/**
 * @return the {@link ServiceLocator} that is managing this ISAAC instance
 */// w w w. j a va  2s  .c o m
public static ServiceLocator get() {
    if (looker == null) {
        synchronized (lock) {
            if (looker == null) {
                if (GraphicsEnvironment.isHeadless()) {
                    log.info("Installing headless toolkit");
                    HeadlessToolkit.installToolkit();
                }

                PlatformImpl.startup(() -> {
                    // No need to do anything here
                });

                ArrayList<String> packagesToSearch = new ArrayList<>(
                        Arrays.asList("gov.va", "gov.vha", "org.ihtsdo", "org.glassfish"));

                boolean readInhabitantFiles = Boolean
                        .getBoolean(System.getProperty(Constants.READ_INHABITANT_FILES, "false"));
                if (System.getProperty(Constants.EXTRA_PACKAGES_TO_SEARCH) != null) {
                    String[] extraPackagesToSearch = System.getProperty(Constants.EXTRA_PACKAGES_TO_SEARCH)
                            .split(";");
                    packagesToSearch.addAll(Arrays.asList(extraPackagesToSearch));
                }
                try {
                    String[] packages = packagesToSearch.toArray(new String[] {});
                    log.info("Looking for HK2 annotations "
                            + (readInhabitantFiles ? "from inhabitant files" : "skipping inhabitant files")
                            + "; and scanning in the packages: " + Arrays.toString(packages));
                    looker = HK2RuntimeInitializer.init("ISAAC", readInhabitantFiles, packages);
                    log.info("HK2 initialized.  Identifed " + looker.getAllServiceHandles((criteria) -> {
                        return true;
                    }).size() + " services");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    return looker;
}

From source file:adalid.commons.properties.PropertiesHandler.java

private static File[] platformsFolders() {
    if (velocity_folders == null || velocity_folders.length == 0) {
        return null;
    }// w  w w  .ja  va 2 s .c  o  m
    String platforms = "platforms";
    File file;
    ArrayList<File> files = new ArrayList<>();
    for (File folder : velocity_folders) {
        file = new File(folder.getPath() + FILE_SEP + platforms);
        if (FilUtils.isVisibleDirectory(file)) {
            files.add(file);
        }
    }
    if (files.isEmpty()) {
        logMissingDirectory(VELOCITY_FOLDER_KEY, platforms);
        return null;
    }
    return files.toArray(new File[0]);
}