Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

Array List Issue

Thread view: 
vsingr - 12 Dec 2005 17:32 GMT
I have been having this unique issue with Array List I am trying add
say about 10 Objects in an Array List and conevr that to an Array.
Later when I parse through the Array i am having an Array of length 10
however i am only having the same element for all the 10 of them. can
anyone out there throw some light onto what i am doing wrong here here
is the peice of Code I am using

Course course = null;

        for(int i=0;i<10;i++){
            course = new Course();
            course.setCourseName( "Course ".concat(Integer.toString(i)));

            aList.add(course);
            System.out.println(course.getCourseName());

        }

        Course[] courses =  (Course[]) aList.toArray(new Course[0]);

Thanks
Sri
Eric Sosman - 12 Dec 2005 17:48 GMT
vsingr wrote On 12/12/05 12:32,:
> I have been having this unique issue with Array List I am trying add
> say about 10 Objects in an Array List and conevr that to an Array.
[quoted text clipped - 15 lines]
>
>         Course[] courses =  (Course[]) aList.toArray(new Course[0]);

   I don't see anything wrong with what you've shown, so
either I've overlooked something or the error is in what
you haven't shown.  Please post a short complete program
that demonstrates your problem.

Signature

Eric.Sosman@sun.com

vsingr - 12 Dec 2005 18:40 GMT
Eric
Here it goes

public class ProblemDemo {

    public static void main( String args[] ) throws Exception
    {

        ArrayList aList = new ArrayList();
        Course course = null;

        for(int i=0;i<10;i++){
            course = new Course();
            course.setCourseName( "Course ".concat(Integer.toString(i)));

            aList.add(course);
            System.out.println(course.getCourseName());

        }

        Course[] courses =  (Course[]) aList.toArray(new Course[0]);

        for (int j=0; j<courses.length; j++){
            System.out.println(courses[j].getCourseName());
        }

    }
}
There is also an Object called course which is defined below

public class Course implements Serializable {

    private static String courseName;

    /**
    * @return
    */
    public static String getCourseName() {
        return courseName;
    }

    /**
    * @param string
    */
    public static void setCourseName(String string) {
        courseName = string;
    }

}
Please add the appropriate import Statements.

Thanks in advance
Sri
Rebecca - 12 Dec 2005 18:56 GMT
Do not declare your variable as static. Is there a reason why you are
doing that. If you remove static from your Course class, it will work

public class Course implements Serializable {

       private String courseName;

       /**
        * @return
        */
       public String getCourseName() {
               return courseName;
       }

       /**
        * @param string
        */
       public void setCourseName(String string) {
               courseName = string;
       }

}
vsingr - 12 Dec 2005 19:02 GMT
Well I had my own reasons for declaring as static. I guess i will have
to work around that now.
thanks
Rebecca - 12 Dec 2005 20:45 GMT
You may want to look into when it makes sense to declare something
static - here's a descent article.

http://www.javaworld.com/javaworld/javaqa/2001-11/03-qa-1121-mrhappy.html
Eric Sosman - 12 Dec 2005 19:37 GMT
vsingr wrote On 12/12/05 13:40,:
> Eric
> Here it goes
[quoted text clipped - 24 lines]
>     }
> }

   That much is fine: You create ten distinct Course
objects, give them names, put them in the ArrayList,
pull them out again in the form of an array, and print
the names.  All is well, so far.

> There is also an Object called course which is defined below
>
> public class Course implements Serializable {
>
>     private static String courseName;

   Aha!  All the Course instances share a single
courseName variable.  When you retrieve the ten
different Course objects from the array and call
their getCourseName() methods, they all return that
same shared courseName.  Ten Courses, only one name.
Without "static," each Course would have its own name,
distinct from the names of the other Courses.

Signature

Eric.Sosman@sun.com

ricky.clarkson@gmail.com - 12 Dec 2005 20:22 GMT
As a general rule, I would avoid non-final static fields, as they are
often used as crude implementations of the Singleton [anti]pattern, aka
global variable.  If you made the above field final you would get
compile errors, and have to look at it a bit closer.

All rules have exceptions, but surely there must be an exception to
that rule.
IchBin - 12 Dec 2005 21:17 GMT
> I have been having this unique issue with Array List I am trying add
> say about 10 Objects in an Array List and conevr that to an Array.
> Later when I parse through the Array i am having an Array of length 10
> however i am only having the same element for all the 10 of them. can
> anyone out there throw some light onto what i am doing wrong here here
> is the peice of Code I am using
[snip code]
This works for me..

List aList = new LinkedList();  // Doubly-linked list
aList = new ArrayList();        //

for (int i = 0; i < 10; i++){
    Course course = new Course();
    course.setCourseName("Course ".concat(Integer.toString(i)));
    aList.add(course);
    System.out.println("Addinng  " + course.getCourseName());
}
Course[] courses = (Course[])aList.toArray(new Course[0]);
for (int i = 0; i < 10; i++){
    System.out.println("Added  " + courses[i].getCourseName());
}
}
}
class Course {
String courseName;
void setCourseName(String courseName) {
    this.courseName = courseName;
}
String getCourseName() {
    return this.courseName;
}
}

Signature

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

vsingr - 12 Dec 2005 21:27 GMT
Thanks all of you for your insights I am grateful for all the
responses\

regards
Sri
Noodles Jefferson - 15 Dec 2005 06:08 GMT
> I have been having this unique issue with Array List I am trying add
> say about 10 Objects in an Array List and conevr that to an Array.
[quoted text clipped - 13 lines]
>
>         }

         Object[] theCourseObjects = alist.toArray()

              for (int i = 0; i < theCourseObjects.length; i++) {

            Course nextCourse = (Course) theCourseObjects[i];
            System.out.println(nextCourse.toString());

              }

> Thanks
> Sri

Signature

Noodles Jefferson
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM

NP: "The Road to Chicago" -- Thomas Newman (Road to Perdition
Soundtrack)

"Our earth is degenerate in these latter days, bribery and corruption
are common, children no longer obey their parents and the end of the
world is evidently approaching."
--Assyrian clay tablet 2800 B.C.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.