The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Storing Objects in a Vector

Posted by Matt Gerrans on October 26, 2001 at 3:03 AM


This is not just a simple matter of changing the Name member variable to
not be static.

Christian, the problem is, when you make a static variable, there is only
one instance of that variable for the whole program, not
one for each object. So the Name variable in the
v1 variable is really the exact same Name
as in v2. When you create v2 you are
just changing this "global" value of VectorItem.Name. By making it not
be static, there could be a different Name for every
VectorItem object you create.

A few other tips, by the way:


  • The standard convention in Java for member variable names is to
    not capitalize the first character of the name,
    but do use capitalization to separate words in variables (for
    example "name" not "Name" and "itemName" not "ItemName."
  • Use static sparingly, when you really do need a single variable
    to be shared by all instances of a class. It is more commonly
    used in combination with final, which results
    in a class constant.
  • You don't have to use the this reference to
    access an object's variable or method, unless there is a name
    clash. An example of a name clash would be if your
    member variable was "name" and your constructor also took
    a parameter called "name." In that case "this.name = name;"
    would be necessary, since "name = name;" would be silly.
  • You might want to use a List (with either ArrayList
    or LinkedList Collection object) instead of a Vector, unless you are
    using an old JDK or you need the thread safety of Vector.
    By the way, List has less verbose methods (add() instead of
    addElement() and so on) and Vector has been retrofitted to
    the List interface, so it can use those, too.
  • The best way to go through all the items in a List (or Vector),
    is with an Iterator (see example, below); it is easy to use and
    will probably have much better performance than your own
    for-loop that accesses each item.

You can download Bruce Eckel's
book Thinking in Java for free.
Also, Sun has nice
online
tutorials
. Based on the fact that you had
everything as static, it looks like you may have more experience with
a procedural language (C, or BASIC perhaps?) and you may want to get
more acquainted with the object-oriented approach. Thinking in Java
kind of takes the approach that the reader knows C and introduces
Java from that perspective.

Finally, here is what your code might look like if you applied
some of the above suggestions (for simplicity, I put both
classes in one file, which required that the ListItem not be
public. However, your practice of having a
separate java file for each class is actually best, especially as
a project grows and the classes become more complex):


import java.util.*;

class ListItem
{
private String name;

public ListItem(String itemName)
{
name = itemName;
}

public String getName()
{
return name;
}
}

public class ListTest
{
static Random random = new Random();

// Initialize the list here or in the constructor,
// but not in main()!
private List itemList = new ArrayList();

public void show()
{
Iterator i = itemList.iterator();

while( i.hasNext() )
System.out.print(((ListItem)i.next()).getName() + " ");
}

public void addSomeCharacters()
{

}

public void addSomeShadyCharacters( int howMany )
{
for( int i = 0; i < howMany; i++ )
{
// This is broken up into many lines for clarity (it is
// possible to lump it all in one statement, but much
// harder to read).
char randomChar = (char)( 'a' + random.nextInt(26) );
Character shadyCharacter = new Character( randomChar );
String itemName = shadyCharacter.toString();
ListItem listItem = new ListItem( itemName );
itemList.add( listItem );
}
}

public static void main( String [] args )
{
ListTest test = new ListTest();

int howMany = 10;
try
{
howMany = Integer.parseInt( args[0] );
}
catch( Exception e )
{
System.out.println( "Failed to read 'howMany' option " +
"from command line, defaulting to " +
howMany + "." );
}

test.addSomeShadyCharacters( howMany );
test.show();
}
}


- mfg




> > Hi there,

> > I tried to use a Vector to store some simple Objects. The problem is, that I don't get the correct global variables of the Objects back. (see source code)
> > Instead of returning A and B, I just get B two times. I don't know the reason. I always get the name of the last added Object x the Vector size.
> > I can't figure out the problem - but maybe you can.

> > Thanks for all answers,

> > Chris.


> > public class VectorItem {
> >
> > private static String Name;
> >
> > public VectorItem(String ItemName) {
> >
> > this.Name = ItemName;
> > }
> >
> > public String getName() {
> >
> > return this.Name;
> > }
> > }

> > ---------------------------------------------------

> > import java.util.Vector;

> > public class Test {
> >
> > private static Vector ObjectVector;
> >
> > public static void show() {
> >
> > for (int i = 0; i < ObjectVector.size(); i++) {
> >
> > System.out.println( ((VectorItem) ObjectVector.elementAt(i)).getName());
> > }
> > }
> >
> > public static void main(String [] argv) {
> >
> > VectorItem v1 = new VectorItem("A");
> > VectorItem v2 = new VectorItem("B");
> >
> > ObjectVector = new Vector();
> >
> > ObjectVector.addElement(v1);
> > ObjectVector.addElement(v2);
> >
> > show();
> > }
> > }





> Change Name in the class VectorItem to be non-static i.e. instance variable.




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us