简体   繁体   中英

Creating a pattern array in Java

This is probably a very simple problem but I'm trying to create an array of patterns and there are some issues. What I've done is below:

Pattern [] aminos = null;
aminos [0] = Pattern.compile("(gct)|(gcc)|(gca)|(gcg)");
aminos [1] = Pattern.compile("(tgt) | (tgc)");
aminos [2] = Pattern.compile("(gat) | (gac)");

There are no syntax errors or anything before I try to run it, but when I try to run it breaks at the 2nd line saying "Null pointer access: the variable aminos can only be null at this location". How do I create a Pattern array then? When I neglected to specify null an error appeared asking me to initialise the array, so I'm unsure what to do now.

I guess I could store all the regex patterns in a String Array and then write a small function to form the patterns as needed but it would be more convenient if I could just make a Pattern array.

Thanks for reading guys!

Here's one simple approach:

Pattern[] aminos = {
    Pattern.compile("(gct)|(gcc)|(gca)|(gcg)"),
    Pattern.compile("(tgt) | (tgc)"),
    Pattern.compile("(gat) | (gac)")
};

Alternatively, you could create an array of the right size to start with:

Pattern[] aminos = new Pattern[3];

That means getting the counting right though - the first version will automatically give you an array of the right size.

Or use a List<Pattern> instead (the collection classes are generally more pleasant to work with than arrays):

List<Pattern> aminos = new ArrayList<Pattern>();
aminos.add(Pattern.compile("(gct)|(gcc)|(gca)|(gcg)"));
aminos.add(Pattern.compile("(tgt) | (tgc)"));
aminos.add(Pattern.compile("(gat) | (gac)"));

You have to initialize the array with the size it will be. Java doesn't have flexible arrays.

Pattern[] aminos = new Pattern[3];
aminos [0] = Pattern.compile("(gct)|(gcc)|(gca)|(gcg)");
aminos [1] = Pattern.compile("(tgt) | (tgc)");
aminos [2] = Pattern.compile("(gat) | (gac)");

If you don't know how many Pattern s you will have, you can use an ArrayList like this:

ArrayList<Pattern> aminos = new ArrayList<Pattern>();
aminos.add(Pattern.compile("(gct)|(gcc)|(gca)|(gcg)");
...

ArrayList s are the flexible version of an array in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM