Accessing member variable

Hello techies,
Iam trying to access the member variables of an object which is added to arrayList.
I had 2 arrayLists.
Now i am converting it into Object[] using toArray()
Now iam comparing these two arraylists.
Now iam trying to access the memeber vairables of each object which is added to arraylist .
But iam unable to access the member variable of each object.
Object a[] = a1.toArray();
          Object b[] = a2.toArray();
          for (int i = 0; i < a.length; i++) {
               System.out.println("inside for loop");
               for (int j = 0; j < b.length; j++) {
// a.
                    int o = compareObjects.compare(a[i], b[j]);
                    System.out.println("returned value is" + o);
Here is my code::
import java.util.*;
import java.io.*;
import java.lang.*;
class exampleObject implements Comparator {
     String s = null;
     int i;
     int o;
     public exampleObject() {
     public exampleObject(int p, int q) {
          i = p;
          o = q;
     public int compare(Object o1, Object o2) {
          exampleObject k = (exampleObject) o1;
          exampleObject kk = (exampleObject) o2;
          // System.out.println("k.i"+k.i);
          // System.out.println("kk.i"+kk.i);
          if (k.i == kk.i) {
               System.out.println("inside if condition" + k.i);
               System.out.println("same i values");
               if (k.o == kk.o) {
                    System.out.println("kk.o");
               } else {
                    System.out.println("same p values");
                    return kk.o;
          return k.i;
class ArrayListObjectCompare {
     // public static BufferedReader readFile;
     public static exampleObject ex;
     public static void main(String args[]) {
          ArrayList a1 = new ArrayList();
          ArrayList a2 = new ArrayList();
          ex = new exampleObject(2, 3);
          exampleObject ex1 = new exampleObject(3, 4);
          exampleObject ex2 = new exampleObject(4, 5);
          exampleObject ex3 = new exampleObject(5, 6);
          exampleObject ex4 = new exampleObject(6, 7);
          a1.add(ex);
          a1.add(ex2);
          a1.add(ex4);
          a2.add(ex1);
          a2.add(ex3);
          exampleObject compareObjects = new exampleObject();
          Object a[] = a1.toArray();
          Object b[] = a2.toArray();
          for (int i = 0; i < a.length; i++) {
               System.out.println("inside for loop");
               for (int j = 0; j < b.length; j++) {
// a[i].k(-----here iam getting error);
                    int o = compareObjects.compare(a[i], b[j]);
                    System.out.println("returned value is" + o);
can any tell me how to access the member variable of each object which is added to arrayList.
I will be very thankful if any body replies or modifies my code.
thanks(inadvance),
ramu

I'm not sure if they work 100% correctly yet after the forum "upgrade" last week, but please use code tags (see button above posting box) when posting code.
You need to cast your Object back to exampleObject:
exampleObject myObj = (exampleObject)a[0];
System.out.println(myObj.i);Or, try using the other "toArray" overload:
exampleObject a[] = a1.toArray(new exampleObject[a1.size()]);Then your "a" array elements are already of class exampleObject, and you don't need to cast each element individually.

Similar Messages

  • Accessing member variable within an anonymous inner class

    I'm getting a compiler error with the following snippet which resides in a constructor (error below):
            final String fullNamesArr[] = new String[ lafsArr.length ];
            String lafNamesArr[] = new String[ lafsArr.length ];
            JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
            for ( int i = 0 ; i < lafsArr.length ; i++ )
                StringTokenizer tokenizer;
                fullNamesArr[ i ] = lafsArr[ i ].getClassName();
                tokenizer = new StringTokenizer( fullNamesArr[ i ] );
                while ( tokenizer.hasMoreTokens() )
                    lafNamesArr[ i ] = tokenizer.nextToken( "." );
                namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
                lafMenu.add( namesMenuItemArr[ i ] );
                namesMenuItemArr[ i ].addActionListener(new ActionListener()
                        public final void actionPerformed(final ActionEvent e)
                            String actionCommand = e.getActionCommand();
                            int iCount = 0;
                            for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                                if ( fullNamesArr[ index ].contains( actionCommand ))
                                    iCount = index;
                                    break;
                            System.out.println( "Setting LAF to '" +
                                                fullNamesArr[ iCount ] + "'" );
                            try
                                UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                            catch ( UnsupportedLookAndFeelException ulafe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Not a valid LAF class." );
                            catch ( ClassNotFoundException cnfe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Class not found." );
                            catch ( InstantiationException ie )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Can't instantiate class." );
                            catch ( IllegalAccessException iae )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Illegal access." );
    DBBuilder.java:1280: cannot resolve symbol
    symbol : method contains (java.lang.String)
    location: class java.lang.String
    if ( fullNamesArr[ index ].contains( actionCommand ))
    ^
    1 error
    BUILD FAILED
    My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
    TIA,
    Jeff

    My question: Why can I access fullNamesArr in other
    spots in the anon-inner class,but not with the
    String.contains() method? BTW, the carrot is under
    the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

  • How to access function from Top Class to Function of class that contain the the member variable of TopClass

    Dear All,
    is there any way that i can access function or member variable of aggregate class.
    i am working in Visual Studio 2010 
    and making win32 dll with mfc Support. i am new in dll system. just learning and doing.
    previously all in exe and i am working this like
    CTestDoc*pDoc = (CTestDoc*)GetTestDocument();
    somevar = pDoc->xDoc.mVar.GetValue (); 
    now i am trying to put all in dll. so getting problem 
    will i get help on this. thanks in advance.
    below code is just an example.
    for example
    // dll 1
    class aaa : public BaseClass
    public:
    int Index;
    char *cName;
    void doSometing()
    if (GetCurBColor() == 125) // how to access GetCurBColor function of the
    color = GetCurBColor();
    long color;
    // dll 2
    class bbb :public BaseClass
    public:
    int Index;
    long lSize;
    long color;
    void doSometing();
    // dll 3
    class DDD
    public:
    vector <aaa> va;
    vector <bbb> vb;
    int cura;
    int curb;
    long GetCurBColor ()
    return vb[curb].color;
    };// MFC doc/view support
    /// in exe in document
    class inExe
    public:
    DDD d;
    void addB()
    { bbb bb;
    bb.color = 152;
    d.vb.push_back(bb);
    bb.color = 122;
    d.vb.push_back(bb);
    bb.color = 1232;
    d.vb.push_back(bb);
    d.curb = 1;
    void addA()
    { aaa aa;
    aa.color = 152;
    d.va.push_back(aa);
    aa.color = 1232;
    d.va.push_back(aa);
    aa.color = 1542;
    d.va.push_back(aa);
    aa.color = 15;
    d.va.push_back(aa);
    d.cura = 2;
    d.va [1].doSometing ();

    Dear All,
    is there any way that i can access function or member variable of aggregate class.
    i am working in Visual Studio 2010
    and making win32 dll with mfc Support. i am new in dll system. just learning and doing.
    previously all in exe and i am working this like
    CTestDoc*pDoc = (CTestDoc*)GetTestDocument();
    somevar = pDoc->xDoc.mVar.GetValue ();
    now i am trying to put all in dll. so getting problem
    What problem?
    The rules of C++ do not change because some of the code ins in a DLL. But the classes in a DLL need to be exported. See for example
    https://msdn.microsoft.com/en-us/library/81h27t8c.aspx
    You should also supply a macro so that the class header can be used in both the DLL and the client. See for example
    http://stackoverflow.com/questions/14980649/macro-for-dllexport-dllimport-switch
    If  you exchange memory between the DLL and the client (as your example will do, because of the std::vector content), you should also be sure to use the same version of the compiler for each module, and to dynamically link to the CRT.
    I would also advise you to start with a less complicated scenario, with just one DLL.
    David Wilkinson | Visual C++ MVP

  • GetVariable() doesn't work in FireFox for object member variables

    I'm trying to access Flash member variables from Javascript
    using GetVariable. The following line of code works for IE but not
    for Firefox:
    var variable = swf.GetVariable("someObject.someProperty");
    In IE, the GetVariable() function returns the correct value
    for the property. However in Firefox, the GetVariable() function
    returns "null" when trying to access the property. If I just try to
    access the object in Firefox (i.e. swf.GetVariable("someObject"), I
    get a string back (instead of the object that I am expecting). If I
    try to access a variable (such as a string) and not an object using
    GetVariable(), this works in both Firefox and IE.
    Any ideas what I am doing wrong? I suspect that my syntax for
    accessing object member variables in Firefox is incorrect but I
    have not been able to find any documentation on the correct syntax.
    Any assistance would be greatly appreciated.
    Thanks.

    Thanks, but this isn't an issue.
    The window.document.flashMovie will return the correct flash
    object/embed flash movie.
    The issue is that the GetVariable method wont return the
    object variable. When you try to get an simple variable that is in
    the _root timeline, it will return the value. Example:
    movie.GetVariable(_url) will return the url of the flash
    movie without any problem.
    But when you create an ActionScript class with
    userName property and then you will create the instance of
    it in the _root, you should be able to get it's value. Example:
    Flash:
    var obj = new SomeClass();
    obj.userName = "peter";
    JavaScript:
    movie.GetVariable("/obj:userName");
    or
    movie.GetVariable("obj.userName");
    This will return
    Peter for IE and null for Forefox/Opera.
    The same when you use the document.embeds[..].

  • Class/member variables usage in servlets and/or helper classes

    I just started on a new dev team and I saw in some of their code where the HttpSession is stored as a class/member variable of a servlet helper class, and I was not sure if this was ok to do or not? Will there be problems when multiple users are accessing the same code?
    To give some more detail, we are using WebLogic and using their Controller (.jpf) files as our servlet/action. Several helper files were created for the Controller file. In the Controller, the helper file (MyHelper.java) is instantiated, and then has a method invoked on it. One of the parameters to the method of the helper class is the HttpServletRequest object. In the method of the helper file, the very first line gets the session from the request object and assigns it to a class variable. Is this ok? If so, would it be better to pass in the instance of the HttpServletRequest object as a parameter to the constructor, which would set the class variable, or does it even matter? The class variable holding the session is used in several other methods, which are all invoked from the method that was invoked from the Controller.
    In the Controller file:
    MyHelper help = new MyHelper();
    help.doIt(request);MyHelper.java
    public class MyHelper {
        private HttpSession session;
        public void doIt(HttpServletRequest request) {
            session = request.getSession();
            String temp = test();
        private String test() {
            String s = session.getAttribute("test");
            return s; 
    }In the past when I have coded servlets, I just passed the request and/or session around to the other methods or classes that may have needed it. However, maybe I did not need to do that. I want to know if what is being done above will have any issues with the data getting "crossed" between users or anything of that sort.
    If anyone has any thoughts/comments/ideas about this I would greatly appreciate it.

    No thoughts from anyone?

  • First operand of . is not an object, so cannot access member WriteLine

    1) I get error like
    First operand of . is not an object, so cannot access member WriteLine. (180,235) Z_REM_STRING.Z_FUNCLIB_FORMULA.FieldFormula Name:RemoveSpace PCPC:691 Statement:11
    2) I have the record called Z_REM_STRING and have one field call FUNCLIB_FORMULA.FieldFormula
    3) the function inside the FieldFormula is
    Function RemoveSpace(&inputString As string) Returns string;
    some log
    Return &temp;
    End-Function;
    the code inside the function is work fine inside the AE
    what mistake that I made?

    Hi
    The part where you have "some log" you have not declared the file.
    Try something like:
         Local File &myFileVar = GetFile("C:\temp\myLogFile.log","W",%Filepath_Absolute);
    where &myFileVar is the file variable you use for the writeline.
    Kind regards
    André

  • Accessing private variables

    I'm a little confused. I know that using private instance variables is good practice, and that the appropriate way to access those variables is with accesser methods (getXXX(), etc.). Since the variables are private, you can't access them by just referring to "testClass.variable", right?
    Well, I was reading up on the Comparable interface today, and found a code example where a class implemented a compareTo() method like this:
    public int compareTo(Object o) {
       if (privateVariable < (TestClass) o.privateVariable) {
          return -1;
       } else {
          return 1;
    }But privateVariable is declared as a private variable. So why is it that you can refer to o.privateVariable in the compareTo() method? Is it just because o is cast as a TestClass object, and the compareTo() method is inside of the TestClass class? Even if that's the case, it still seems weird to me; if privateVariable is declared private, I'd think that any reference to a TestClass.privateVariable variable would throw an exception, even if the reference is within the TestClass. This just seems different to me than referring to the privateVariable variable within TestClass, because that obviously refers to the member of the current instance, not a different instance.
    Anyway, any explanation would be appreciated.
    Rich

    Yes, 'private' means 'private to this class', not 'private to this object'.
    In this way, it behaves somewhat like a 'friend' variable. The basic idea of making variables private is to hide the implementation behind a class, which still holds even with the compareTo method (you can't use it to figure out that there's a variable called 'privateVariable', when using it from outside your class.)

  • Interface member variable by defaultly static ?

    Hi,
    The interface member variable by defaulty public,static,final.
    But i have one doubt.
    It is public because it has to access out side the interface.
    It is final because the value never changes
    Why it should be static ???
    Thanks,
    Narendra babu.B

    Member variables are an implementation detail. Java does not allow multiple implementation inheritance. Java does allow multiple subtyping through interfaces. So interfaces can't have member variables.
    Consider the diamond of death:
    interface A
        int x;
    interface B extends A
    interface C extends A
    interface D extends B, C
    }See the problem now?

  • Static member variable conundrum

    I'm using an abstract base class so that subclasses can share common functionality.
    Each subclass needs a static member variable (a String) that needs to be accessed from the abstract base class in some of it's methods.
    This is where the problem is; I would like to declare an abstract variable in the base class so that the base class methods can use the variable, but you can't make an abstract variable static.
    Is there a way around this or am I approaching this problem from the wrong direction?

    I can't remember if you can override static methodsTested this and determined that you can't. The superclass static gets called. Makes sense.
    I also tested my suggested code, and made a few improvements ... maybe it isn't quite so ugly after all (can you tell that I'm slogging through some boring stuff?):
    public class Tester1
        protected static HashMap _stringTable = new HashMap();
        static
            _stringTable.put(Tester1.class, "Tester 1");
        protected String getString()
            return (String)_stringTable.get(this.getClass());
        public static void main(String[] argv)
            Tester1 t1 = new Tester1();
            Tester2 t2 = new Tester2();
            Tester1 t3 = new Tester2();
            System.out.println("t1.getString() = " + t1.getString());
            System.out.println("t2.getString() = " + t2.getString());
            System.out.println("t3.getString() = " + t3.getString());
    public class Tester2 extends Tester1
        static
            _stringTable.put(Tester2.class, "Tester 2");

  • Default initialisation of member variables and local variables

    I don't understand why member variables are initialized with default values by Java.
    Objects are initialized with "null" and primitives with "0", except boolean, which is initialized with "false".
    If these variables are used locally they are not initialized. The compiler requires them to be initialized by the programer, for example "String s = null".
    Why? What is the use of that difference?
    And why are arrays always initialized with default values, no matter if they are member variables or local variables? For example String[] s = new String[10]; s[0] to s[9] are initialized with "null", no matter if "s" is a local or member variable.
    Can someone please explain that strange difference, why it is used? To me it has no sense.

    Most of the time I have to initialize a local variable
    with "String s = null" in order to use it because
    otherwise the compile would complain. This is a cheap
    little trick, but I think everyone uses it.
    I wouldn't agree with "most of the time". The only cases where it is almost necessary to do that is when the variable should be initialized in a loop or a try-catch statement, and that doesn't happen too often.
    If local variables were initiliazed automatically without a warning it would be a Bad Thing: the compiler could tell when there is a possibility that a variable hasn't been assigned to and prevent manymanymany NullPointerExceptions on run time.
    And you didn't answer me why this principle is not
    used with arrays if it is so useful as you think.
    Possibly it is much more difficult to analyse the situation in the case of arrays; what if values are assigned to the elements in an order that depends on run time properties such as values returned from a random number generator.
    The more special rules one has to remember, the more
    likely one makes errors.I agree, but what is the rule to remember in this case?

  • How can I access global variables in a loaded Applescript?

    How can I access global variables in a loaded script, in Xcode, ApplescriptObjC? Basically, I have a global variable defined in my parent script using "property", and I need to modify objects connected to those variables inside of a loaded script.
    Example:
    Parent script:
    script AppDelegate
    property myTextField : missing value
    //linked to a text field object
    tell myScript to myAwesomeHandler_()
    end script
    Loaded script:
    on myAwesomeHandler_()
    myTextField's setStringValue_("The new Xcode is so glitchy ugh")
    //changes value of linked text field of parent script
    end myAwesomeHandler_
    The problem is, the variable is undefined in the Loaded script, and I need it to have the same value as the parent script, and I don't want to pass the variable through the Handler. Any ideas?

    I think want you are looking to do will need to be done in two steps. Because myTextField needs to be a property for the ObjectiveC part of the code you cannot turn it into a global.
    However if you make a temporary variable global assign the string to it in the handler then set myTextField off of it.
    global myTextFieldGlobal
    script AppDelegate 
    property myTextField : missing value 
    //linked to a text field object 
    tell myScript to myAwesomeHandler_() 
    myTextField's setStringValue_(myTextFieldGlobal)
    end script 
    on myAwesomeHandler_() 
    set myTextFieldGlobal to "The new Xcode is so glitchy ugh"
    //changes value of linked text field of parent script 
    end myAwesomeHandler_ 
    I know you stated you did not want the handler to return a value but I have to ask why? Global's, imo, are not a good idea and really should be used as a last resort.
    One other possibility is to pass a reference to the property to the handler. Not sure if that works in AS of if that would satisfy our requirement of not passing the variable through the handler
    <edit>
    Another though have you tried to define the property outside the script?  That is
    property myTextField : missing value
    script AppDelegate
    Not sure if that will work.
    You might also want to have a look at Scope of Properties and Variables Declared in a Script Object

  • Access a variable in the Adobe form for Java Scripting

    Hi,
    I am unable to know how to access the variable in a Adobe form.
    The variable is field of an internal table. My adobe form structure is as follows
    MAIN_PAGE->FORMSET->FirstFORM->EXT.
    in the EXT subform the variable(cust)  exists.
    The cust is in turn an internal table.

    Hello Sreelatha,
    I think we cannot hide a page.  as in, page is the main container.  In a container, we can hide any field using some scripting.  Even though if we hide the field, it is present on page but not visible. 
    but if some logic is there, please let me know.
    Thanks,
    Rakesh.
    Edited by: rakhi966 on Sep 8, 2011 8:54 PM

  • Access custom variable value in web.xml context-param?

    My requirement or need is to access a variable value either in a class in my Model project or a backing bean in my View project. For example, one variable I need to access is an application server I am integrating with - 'testserver' or 'productionserver' - I want to be able to configure this within an external file so that I do not have to re-compile my application to change the variable.
    I was thinking about placing this variable in the web.xml <context-param> section as:
    <context-param>
    <param-name>servername</param-name>
    <param-value>testserver</param-value>
    </context-param>
    I need to access this value within a class (not a servlet) on an Application Module service method, though if needed, I could access it from a backing bean and pass it to the service method (less desirable.) Is this a good approach and how do access this variable from within a Java class including any imports I need to do (code example)?
    Thanks and Happy New Year!
    Hopefully most everyone is out spending time with friends and family versus stuck trying to complete a project like me...

    I found an example from SRDemo that provides what I was looking for:
    String serverhostaddress =
    FacesContext.getCurrentInstance().getExternalContext().getInitParameter("param-name-var-in-webxml");

  • Why can't I access the variables in my threads?

    hello.
    another question about threads..
    ==========================
    I have an inner class that implements Runnable (i.e. a thread) and has a variable in it. I want to be able to access that variable from outside the thread class so that I can set or retrieve the variable.
    here is the code for the program
    class myClass
         public static void main(String[] args)
              myClass c = new myClass();
         myClass()
              Thread t = new Thread(new myThread());
              t.number = 1;
              t.start();
         class myThread implements Runnable
              int number = 0;
              public void run()
         }//end myThread
    }//end myClassthe line
    t.number = 1;
    where I try to set the number variable to 1 gives me an error (in the MyClass constructor)
    This is my error
    AccessThreadVars.java:11: cannot find symbol
    symbol  : variable number
    location: class java.lang.Thread
              t.number = 1;
                        ^
    1 errorif I put a method in myThread, and then try to call that method from myClass (via t.MethodName()) it gives me that same error telling me it can't find it..
    what am I doing wrong? how can I get access my thread's variables and methods??

    1. Type names should start with an uppercase letter
    2. t is defined as a Thread, not as a myThread
    (which, may I insist, should be "MyThread"), so the
    compiler has no means of detecting that "number" is
    an accessible field of the object... which wouldn't be accessible anyway, cause you're trying to get attributes from your Runnable after wrapping it inside a Thread.
    Why don't you do something like :
    MyThread t = new MyThread();
    t.number = 1;
    new Thread(myThread).start();?
    I bet you don't use Thread's own methods anyway...

  • Accessing the variable in field symbol of nested internal table

    Hi,
    I am unable to access the variable in field symbol.
    The data in field symbol has nested structure. We need to access a variable in nested structure.
    Please find the code below:
          LOOP AT <i_fincorp> into <fs_fincorp>.
            l_madefor = <FS_FINCORP>-data_UI-ZZ0010.
          ENDLOOP.
    datatype of <i_fincorp> is type any table and <fs_fincorp> is type any.
    there is a structure 'data_ui' in <i_fincorp> and we need value of field 'ZZ0010' in data_ui structure.
    But, we are getting syntax error for statement in loop stating "There is no component like 'data_ui' in <fs_fincorp>".
    Can anyone please help me solving this issue.
    Regards,
    Santosh

    So simply access it dynamically
    data: nested_field type c length 50.
    field-symbols <nested_field> type any.
    "build the nested field name dynamically
    concatenate
           'DATA_UI'    "first give structure name
           'ZZ0010'  "then give field name (all in uppercase!)
    into nested_field
    separated by '-'.  "now you have DATA_UI-ZZ0010
    "so assing this nested field
    LOOP AT <i_fincorp> into <fs_fincorp>.
       assign component (nested_field) of structure <fs_fincorp> into <nested_field>. 
    ENDLOOP.
    Regards
    Marcin

Maybe you are looking for

  • How do i cancel my order without an apple id?

    my mum ordered 2 things from apple store then realized that she ordered the wrong thing. to purchase anything, you;'ll need to sign in with an apple id first or sign in as a guest. she signed in as guest. then, when we tried to change/cancel order, a

  • Nano doglocked - can't restore

    I have tried to restore my nano. When it is plugged in, iTunes prompts that "iTunes has detected an iPod in recovery mode. You must retore this iPod before it can be used with iTunes"... I click "ok" and restore it. It appears to go through the resto

  • Test samples with JBoss?

    Hello, I downloaded jsf-1_2_02.zip just now. I want to test sample apps in the archive. According to sample instructions, I shall install glassfish firstly. But currently, I only have JBoss4.0.2. Can I run the samples in JBoss? What I must do? I drop

  • Exception LOG_NOT_FOUND

    Hi SDNers, After upgrading from 4.6C to ECC6, I got a dump when I use the function COMMON_LOG_READ_PLAIN for BDC logs. In ECC6 version, this function uses the function RSTS_READ_OBJECT_DIRECT. This last function, only allows jobs log (JOBLGX) but not

  • EarlyWatch Report

    Ladies/Gents Can someone please confirm if I need to put on / activate statistics (RSA1->Tools->Settings for BI Statistics) to obtain query statistics results in the EarlyWatch report? I understand that statistics needs to be switched on if I want to