开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜