Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-1240021

Method toString of Vector fails for null elements

XMLWordPrintable

    • 1.2alpha2
    • sparc
    • solaris_1
    • Not verified

      The inner loop of the toString method of class Vector in java.util
      looks like this:

      for (int i = 0 ; i <= max ; i++) {
      String s = e.nextElement().toString();
      buf.append(s);
      if (i < max) {
      buf.append(", ");
      }
      }

      Observe that if any item in the Vector is null, a NullPointerException
      will be thrown. This is not desirable. Better would be to code it as

      for (int i = 0 ; i <= max ; i++) {
      buf.append(e.nextElement().toString());
      if (i < max) {
      buf.append(", ");
      }
      }

      The append method of StringBuffer will handle the case of a null pointer
      properly.

      ============================================================================

      daniel.indrigo@Canada 1997-08-26

      I still get this problem in 1.2_EA2 on Solaris and win32

      import java.util.*;

      public class ddd {
      public static void main(String args[]) {
      Integer a = new Integer(1);
      Integer b = new Integer(2);
      Integer c = new Integer(3);
      Integer d = new Integer(4);
      Vector v = new Vector(0,2);
      v.setSize(5);
      System.out.println("Inside main()");
      System.out.println(v.size());
      v.addElement(a);
      System.out.println("Add a, size is " + v.size() +", v = " + v);
      v.addElement(b);
      System.out.println("Add b, size is " + v.size() +", v = " + v);
      v.addElement(c);
      System.out.println("Add c, size is " + v.size() +", v = " + v);
      v.insertElementAt(d, 2);
      System.out.println("Insert d at 2, size is " + v.size() +", v = " + v);
      }
      }

      Inside main()
      5
      java.lang.NullPointerException
      at java.util.Vector.toString(Vector.java)
      at java.lang.StringBuffer.append(StringBuffer.java)
      at ddd.main(ddd.java:14)

            tlindholsunw Timothy Lindholm (Inactive)
            duke J. Duke
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: