From arrayList to long []

I am making a method that should return a long []. It looks like this:

public long[] parseString(String input)

line input:

  • 1, 3, 4
  • 10, 30, 40, 50

Inside parseString, I use a regex to get all numbers and add them to an ArrayList, since I can't know how many matches it will find.

In the end, I create long [] with the size of arrayList and do a for each to add it to long [] var.

Another way: First count each event with

while ( matcher.find() ) size++;

and then with size create a long [] of size and do: matcher.reset () and now save the long values ​​in the variable long [].

What do you think is the best?

Is there a better way to do this?

Remember that I cannot change the method signature :(

+3
7

- Java, List<Long>.toArray(Long[]) . , , - - .

, , , , . , .

+4

Google guava-libraries ( !), Longs :

return Longs.toArray(foundLongs);

-!

+10
public long[] parseString(String input) {

        final String[] parsed = input.split(",\\s?");
        final long[] values = new long[parsed.length];

        for (int i = 0; i < parsed.length; i++) {
            values[i] = Long.parseLong(parsed[i]);
        }

        return values;
}
+3
@Test
public void testParsing() throws Exception {
    String input = "1,3,5,6,33";
    long[] parsed = parseString(input);
    assertEquals(5, parsed.length);
    assertEquals(1, parsed[0]);
    assertEquals(3, parsed[1]);
    assertEquals(5, parsed[2]);
    assertEquals(6, parsed[3]);
    assertEquals(33, parsed[4]);
}
public long[] parseString(String input) {
    String[] split = input.split(Pattern.quote(","));
    long[] arr = new long[split.length];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = Long.parseLong(split[i]);
    }
    return arr;
}
+2

You cannot use toArray in this case. ArrayLists store only objects, not primitives. This way you cannot store int, longs, etc. You will have to either store all objects as Long objects, or create a static longs array yourself.

+1
source
List<Long> lErrors = new ArrayList<Long>();
lErrors.add(10L);
Long[] arr = null;
arr = new Long[lErrors.size()];
lErrors.toArray(arr);
0
source

I think you can also do something like.

public long[] parseString(String input)
{
            //1. Split with comma separated
            int nLength = input.Split(new char[] { ',' }).Length;
            long[] arList = new long[nLength];

            for (int i = 0; i < nLength; i++)
            {
                arList[i] = long.Parse(input.Split(new char[] { ',' })[i].ToString());
            }

            return arList;
}

Using:

long[] l = parseString("10, 30, 40, 50");
-1
source

Source: https://habr.com/ru/post/1722260/


All Articles