简体   繁体   中英

Java: Static string array on server side class

I want to keep a static string array to save variables passed from the client when it calls the server, and then to be able to access them from the client with a getter.

for some reason i can only get very basic type (int instead of Integer for instance) to work, everything else throws a null pointer exception.

here is a code snippet. (using GWT)

@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements AddElection
{

    //this seems to be throwing a NullPointerException:
    static String[] currentElections;
    static int index;

    public String electionServer(String input) {
        // save currently running elections 
        currentElections[index] = input;
        index = index + 1;

        // TODO: getcurrentElections

So. my question is, if i want to temporarily store a string array at the server side and be able to access it, how would i do this in google web toolkit? thanks!

You havn't initialized your static array.

At least you have to do something like this:

static String[] currentElections = new String[ 100 ];

But it seems that your array could grow with time, so it's better to use a collection class instead:

static List<String > currentElections = new ArrayList<String >();

public String electionServer(String input) {
    // save currently running elections    
    currentElections.add( input );
}

But be careful if this method can be called simultaneously from several clients. Then you have to synchronize access like this:

static List<String > currentElections = 
    Collections.synchronizedList( new ArrayList<String >() );

Your array is not initialized. Btw, you should not use static variables in a multi threaded applications.

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