Static method doubt

Hi,
I have a doubt using static methods:
If 2 users call the same static method wih diferente parameters, the parameters of first user are changed?
Thanks,
rjc

I already read that the only problem is if i acess
and change static variables, in these cases i have
to synchronize the method, is this true?Certainly, it is. If more than one thread are trying to change the same "thing" by using a method, you have to synchronize this method. Or you can synchronize this "thing", too.

Similar Messages

  • Static method and variables doubts

    i have a doubt
    i have the following method
    private static void checkActionType(String action) {
    if (action.startsWith(" a")) {
    ++totalAddedActions;
    } else if (action.startsWith(" c")) {
    ++totalChangedFolders;
    } else if (action.startsWith(" p")) {
    ++totalPersonalizedActions;
    } else if (action.startsWith(" r")) {
    ++totalRemovedActions;
    } else if (action.startsWith(" v")) {
    ++totalViewedActions;
    } else if (action.startsWith(" u")) {
    ++totalUpdateActions;
    to use it, i need to declare my int variables static, because im calling this method from another static method that is called by main method.
    but this can cause me problems ?
    if i have two instances of this class running, my statics int will show the right value?
    there is a better approach?

    Here is my class, i want some advices to know if i am doing right, because everything is a little new for me.
    My class, read a log file and based upon a regular expression, it can retrieve a general statistic or a personal statistic.
    package br.com.organox.aggregator;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Vector;
    import org.apache.oro.text.regex.*;
    public class LogFileReader {
    private static Pattern regexpPattern;
    private static PatternMatcher patternMatcher;
    private static PatternCompiler patternCompiler;
    private static PatternMatcherInput patternInput;
    private static MatchResult matchResult;
    private static final String patternString = "^[^\']+User\\s+\'([^\']+)\'[^\']+session\\s+\'([^\']+)\'\\s+(\\S+)";
    // Integers used to store number of user, sessions and specific actions
    private static int totalUsers;
    private static int totalSessions;
    private static int totalAddedActions;
    private static int totalChangedFolders;
    private static int totalPersonalizedActions;
    private static int totalRemovedActions;
    private static int totalUpdateActions;
    private static int totalViewedActions;
    public static void main(String[] args) {
    if (args.length == 0) {
    System.out.println("No file name was specified");
    printClassUsage();
    } else if (args.length == 1) {
    printGeneralData(args[0]);
    } else if (args.length == 2) {
    System.out.println("You must set file name, data value and data type in order to " +
    "this class run properly");
    printClassUsage();
    } else {
    printSelectedData(args[0],args[1],args[2]);
    public static void printGeneralData(String fileName) {
    String data = "";
    //Users and the Session Vector are used to avoid count repeated values.
    Vector usersVector = new Vector();
    Vector sessionVector = new Vector();
    patternCompiler = new Perl5Compiler();
    patternMatcher = new Perl5Matcher();
    try {
    regexpPattern = patternCompiler.compile(patternString);
    } catch (MalformedPatternException mpe) {
    System.out.println("Error Compiling Pattern");
    System.out.println(mpe.getMessage());
    try {
    FileReader fileRead = new FileReader(fileName);
    BufferedReader buffRead = new BufferedReader(fileRead);
    while ((data = buffRead.readLine())!= null) {
    patternInput = new PatternMatcherInput(data);
    while(patternMatcher.contains(patternInput,regexpPattern)) {
    matchResult = patternMatcher.getMatch();
    // Avoid to insert repeated data in user and session Vectors
    if (usersVector.lastIndexOf(matchResult.group(1)) == -1) {
    usersVector.add(matchResult.group(1));
    if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
    sessionVector.add(matchResult.group(2));
    increaseActionType(matchResult.group(3));
    for (int i=0;i<usersVector.size();i++) {
    totalUsers++;
    for (int i=0;i<sessionVector.size();i++) {
    totalSessions++;
    fileRead.close();
    buffRead.close();
    } catch (IOException ioe) {
    System.out.println("An I/O error occurred while getting log file data");
    ioe.printStackTrace();
    System.out.println("Users logged : " + totalUsers);
    System.out.println("Sessions opened : " + totalSessions);
    System.out.println("Added contents : " + totalAddedActions);
    System.out.println("Changed folders : " + totalChangedFolders);
    System.out.println("Personalized contents : " + totalPersonalizedActions);
    System.out.println("Removed contents : " + totalRemovedActions);
    System.out.println("Viewed Contents : " + totalViewedActions);
    System.out.println("Updated contents : " + totalUpdateActions);
    public static void printSelectedData(String fileName,String value,String valueType) {
    String data = "";
    String user = "";
    //Flag used to print the right result on screen
    String printFlag = "";
    Vector sessionVector = new Vector();
    Vector userVector = new Vector();
    Vector actionVector = new Vector();
    patternCompiler = new Perl5Compiler();
    patternMatcher = new Perl5Matcher();
    try {
    regexpPattern = patternCompiler.compile(patternString);
    } catch (MalformedPatternException mpe) {
    System.out.println("Error Compiling Pattern");
    System.out.println(mpe.getMessage());
    try {
    FileReader fileRead = new FileReader(fileName);
    BufferedReader buffRead = new BufferedReader(fileRead);
    while ((data = buffRead.readLine())!= null) {
    patternInput = new PatternMatcherInput(data);
    while(patternMatcher.contains(patternInput,regexpPattern)) {
    matchResult = patternMatcher.getMatch();
    if (valueType.equalsIgnoreCase("-user")) {
    printFlag = "userPrint";
    if ((matchResult.group(1).equalsIgnoreCase(value))) {
    userVector.add(matchResult.group(1));
    // avoid insert a repeated value inside session vector.
    if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
    sessionVector.add(matchResult.group(2));
    increaseActionType(matchResult.group(3));
    if (userVector.size() == 0) {
    printFlag = "userPrintError";
    } else if (valueType.equalsIgnoreCase("-session")) {
    printFlag = "sessionPrint";
    if ((matchResult.group(2).equalsIgnoreCase(value))) {
    user = matchResult.group(1);
    sessionVector.add(matchResult.group(2));
    increaseActionType(matchResult.group(3));
    if (sessionVector.size() == 0) {
    printFlag = "sessionPrintError";
    } else if (valueType.equalsIgnoreCase("-action")) {
    printFlag = "actionPrint";
    if ((matchResult.group(3).equalsIgnoreCase(value))) {
    if (userVector.lastIndexOf(matchResult.group(1)) == -1) {
    userVector.add(matchResult.group(1));
    actionVector.add(matchResult.group(3));
    if (actionVector.size() == 0) {
    printFlag = "actionPrintError";
    fileRead.close();
    buffRead.close();
    } catch (IOException ioe) {
    System.out.println("An I/O error occurred while getting log file data");
    ioe.printStackTrace();
    if (printFlag.equals("userPrint")) {
    for (int i=0;i<sessionVector.size();i++) {
    totalSessions++;
    System.out.println("Sessions opened by user " + value + " : " + totalSessions);
    System.out.println("Added contents by user " + value + " : " + totalAddedActions);
    System.out.println("Changed folders by user " + value + " : " + totalChangedFolders);
    System.out.println("Personalized contents by user " + value + " : " + totalPersonalizedActions);
    System.out.println("Removed contents by user " + value + " : " + totalRemovedActions);
    System.out.println("Viewed contents by user " + value + " : " + totalViewedActions);
    System.out.println("Updated contents by user " + value + " : " + totalUpdateActions);
    } else if (printFlag.equals("userPrintError")) {
    System.out.println("This user " + value + " was not found on log file");
    } else if (printFlag.equals("sessionPrint")){
    System.out.println("Session " + value + " was opened by user " + user);
    System.out.println("Added contents by session " + value + " : " + totalAddedActions);
    System.out.println("Changed folders by session " + value + " : " + totalChangedFolders);
    System.out.println("Personalized contents by session " + value + " : " + totalPersonalizedActions);
    System.out.println("Removed contents by session " + value + " : " + totalRemovedActions);
    System.out.println("Viewed Contents by session " + value + " : " + totalViewedActions);
    System.out.println("Updated contents by session " + value + " : " + totalUpdateActions);
    } else if (printFlag.equals("sessionPrintError")){
    System.out.println("This session " + value + " was not found on log file");
    } else if (printFlag.equals("actionPrint")){
    System.out.println("Action " + value + " was performed " + actionVector.size() +
    " times for " + userVector.size() + " different user(s)");
    } else if (printFlag.equals("actionPrintError")){
    System.out.println("This action " + value + " was not found on log file");
    } else {
    System.out.println("Wrong search type!");
    System.out.println("Accepted types are: ");
    System.out.println("-user -> Search for a specified user");
    System.out.println("-session -> Search for a specified session");
    System.out.println("-action -> Search for a specified action");
    private static void increaseActionType(String action) {
    if (action.startsWith("a")) {
    ++totalAddedActions;
    } else if (action.startsWith("c")) {
    ++totalChangedFolders;
    } else if (action.startsWith("p")) {
    ++totalPersonalizedActions;
    } else if (action.startsWith("r")) {
    ++totalRemovedActions;
    } else if (action.startsWith("v")) {
    ++totalViewedActions;
    } else if (action.startsWith("u")) {
    ++totalUpdateActions;
    }

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Static methods in Transfer Objects

    Hi all,
    I have a doubt about Transfer Object:
    Is it possible to have a static method (or field)
    inside a Transfer Object returned from
    a Session Bean to a Client ?
    Many thanks in advance,
    Moreno

    Static fields, yeah, they'd cause some interesting problems, so are not a good idea in TOs. You can do it, but YMMV (Your Mileage May Vary).
    Static method? I'd get rid of it and put it in a utility class or somewhere else. Static methods are pretty meaningless when applied to TOs. The idea is to encapsulate data and some behavior - not provide procedural functionality.

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • Best practice for using static methods

    When i want to call a static method, should i call:
    1) classInstance.staticMethod()
    or should i call
    2) ClassName.staticMethod()??
    is the first style bad programming practice?

    dubwai: which compiler?I had assumed that this was what the JLS specifies, but intsead, it goes into length how to make the runtime environment treat calls to static methods on instances as if they were static calls on the variable's type.
    However, I imagine anyone creating a compiler would go ahead and compile calls to static methods on instances to static calls on the variable's type instead of going through the effort of making the runtime environment treat calls to static methods on instances as if they were static calls on the variable's type.
    But of course, it is concievable that somone didn't in their compiler. I doubt it but it is possible. Sun does compile calls to static methods on instances to static calls on the variable's type:
    public class Garbage
        public static void main(String[] args)
            Garbage g = null;
            method();
            g.method();
        public static void method()
            System.out.println("method");
    public class playground.Garbage extends java.lang.Object {
        public playground.Garbage();
        public static void main(java.lang.String[]);
        public static void method();
    Method playground.Garbage()
       0 aload_0
       1 invokespecial #1 <Method java.lang.Object()>
       4 return
    Method void main(java.lang.String[])
       0 aconst_null
       1 astore_1
       2 invokestatic #3 <Method void method()>
       5 invokestatic #3 <Method void method()>
       8 return
    Method void method()
       0 getstatic #4 <Field java.io.PrintStream out>
       3 ldc #5 <String "method">
       5 invokevirtual #6 <Method void println(java.lang.String)>
       8 return

  • Synchronized and static methods

    I've got a doubt: is it possible to apply syncrhonized to a static method? I know that synchronized takes a lock on the current object, but in the case of a static method there could be no object.
    So how can I synchronize a static method?
    Thanks,
    Luca

    previous X POST(s) :
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411296
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411285
    http://forum.java.sun.com/thread.jsp?forum=31&thread=390499
    http://forum.java.sun.com/thread.jsp?forum=31&thread=374388
    http://forum.java.sun.com/thread.jsp?forum=31&thread=325358
    BOTTOM LINE : Search the forum b4 posting.
    rgds.

  • Why are static methods called with null references,valid ?

    This is my code :
    package inheritance;
    public class inh6{
         public static void method(){
         System.out.println("Called");
         public static void main(String[] args){
              inh6 t4 = null;
         t4.method();
    O/P :
    CalledHere t4 is a null reference and yet we are able to call a method on it,why is null pointerexception not thrown.Why are we able to call static methods using null references ?
    t4 is null means it doesnot refer to any memeory address,hence how is method() called correctly.
    I hope i am clear. :)
    Thank you for your consideration.

    punter wrote:
    jverd wrote:
    Memory addresses have nothing to do with it. I doubt memory addresses are even mentioned once in the JLS.
    By memory address i mean the memory location the reference is pointing to.I know what you mean. But if you think it's relevant, can you show me where in the JLS it says anything about memory locations?
    >
    You can do that because a) t4's type is "reference to inh6" and b) method() is declared static, which means that you don't need an object to call it, just the class. That class comes from the compile time type of t4. The fact that t4 is null at runtime is irrelevant.
    So at compile time the type of t4 is inh6 and hence the method is called.Is it ? Had method() not been static a NullPointerException would have been thrown.Correct.
    With non-static, non-private, non-final methods, which implementation of the method gets called is determined at runtime, buy the class of the object on which it's being called. If any one of those "non"s goes away, then the method is entirely determined at compile time, and in the case of static methods, there's no instance necessary to call the method in the first place.

  • Static method decisions

    Dear all experts,
    I have got some problems understanding when to use static methods or passing the classes through constructor.
    I have got a class which needs to be accessed by several classes and also the classes inside the classes etc....
    Instead of passing classes around, should I just create a single static class which can be accessed by all the classes without needing to instantiate the class?
    I found that, i particularly in doubt when there are classes like "TableParser", "PropertiesReader" etc which some classes deep down in the hierarchy need access to those classes...
    Also, making the class static would it decrease the security of the whole program?? Say if i have got an encrytion class which does all the encrypt and decrypt, if i let it be static, isn't it easier to let people accessing the method? the same applies to properties editor etc??
    Any help would be really appreciated.
    Thx

    thx again jverd... (remember the security question? :)
    )I remember your id, but I didn't recall which thread(s) I had seen it in.
    >
    based on the understanding of what you said, do you
    mean that, if i am only using a class to store or read
    a setting file, it's ok to let it static? (so that all
    classes can access it whenever they like without
    passing the parser class to classes?)Um, again, you're terminology's a little off, so I'm not sure exactly what you mean, and even the description "store or read a seting file" could have a couple of interpretations.
    For example....You read the file once, and the config data it constains is accessible throughout your app and never changes. This might be a candidate for a class that only had static methods, but it would be kind of inflexible. What if later some other part of your app, or some other library that you develop that your app is going to use, wants to get its configuration from a file. In that case, I might want to have a couple instances of that class around. One for the global config that reads one file, and another for the config for that library that might read another file.
    I'd probably not even think about it as "reading a settings file." Rather, I'd see that as two parts: providing config settings to the app via a class, and reading a file to populate that class. The settings would exist independent of the fact that you can populate them from a file.
    I'd think about how I want to use them and decide whether to instantiate the class or use static methods based on that. Separately, I'd think about how this class or an instance of it is gonna get popuated with data from outside the program.
    I might decide to have different instances hold different sets of config data, and therefore use instance (non-static) methods to access the data in each of those instances, but I might register the instances--say by name, or maybe just in a list--and I could use a static method to acess the map or list: Config dbConfig = Config.getConfig("database"); Also, I wouldn't generally make a decsision on whether to use class methods or instance methods based on not having to pass a parameter.
    If you're thinking "I'd like to use static because it's easier. Can I get away with it here," then you're viewing objects as a burden to be avoided, which kind of defeats the purpose of using OO techniques in the first place.

  • Help on calling static method in a multithreaded environment

    Hi,
    I have a basic question.. pls help and it is urgent.. plss
    I have a class with a static method which does nothing other than just writing the message passed to a file. Now i have to call this static method from many threads..
    What actually happens ???
    Does all the thread start to execute the static method or one method executes while the other threads wait for the current thread to complete execution?. I am not talking about synchronizing the threads...my question is what happens when multiple threads call a static method??
    Pls reply.. I need to design my project accordingly..
    Thanks
    Rajeev

    HI Omar,
    My doubt is just this..
    I wanted to know what might happen if two threads try to access a static method.. Logically only one thread can use the method since it is only only copy... but i was wondering what might happens if f threads try to access the same static method.. My Situation is this.. I have a cache which is just a hash table which will be only one copy for the whole application.. No when i get a request I have to check if the id is avaible in the cache. if it is available i call method 1 if not i call method2. Now Ideally the cache should be a static object and the method to check the id in the cache will be a normal instance method..
    I was just wondering what might happen if i make the method static.. If i can make it static i can can save a lot of space by not creating the object each time.. u know what i mean.. That y i wanted to know what happens..
    Rajeev

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • Can you set a global EntityResolver (via system property, or static method)

    I'm trying to set a customized EntityResolver (telling the xml parser where to look for XML schema files).
    Usually, you'd use the standard syntax - somehting like:
    SaxParser parser=new SaxParser();
    parser.parser.setEntityResolver(myResolver);
    However, I was wondering whether you can set a "global" EntityResolver, to be used as default for all parsers ?
    Maybe this can be done through some system property, or a static method somewhere in the parsing XML ?
    (BTW, I need it because I'm using some third-party API, that encapsulates a SaxParser, but won't let me access it, so I can't configure it directly).
    thanks.

    I don't think you can.
    What is possible is to set content on the folder resource itself; that would be returned instead of the page you mentioned.

Maybe you are looking for