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 / September 2006

Tip: Looking for answers? Try searching our database.

Adding Contents of a Vector

Thread view: 
Vera - 07 Sep 2006 07:19 GMT
I'm trying to add together all the contents of the vector. This is what
I wrote and the compiler is telling me I can't use the plus. Is there
another way?

for (int count = 0; count < vectorSize; count++)
{
       sum += tokens.elementAt(count);
}
Ralf Seitner - 07 Sep 2006 08:43 GMT
Vera schrieb:
> I'm trying to add together all the contents of the vector. This is what
> I wrote and the compiler is telling me I can't use the plus. Is there
[quoted text clipped - 4 lines]
>         sum += tokens.elementAt(count);
> }

Hi!
For such questions write the complete error message of the compiler!
(copy&paste)

What type is sum?
What type are the elements of your vector "tokens"?
Which java-version do you use? If you use 1.5, do you use generics?

I think the problem may be, your vector contains Objects, because you
did not use generics and did not specify the Vector only to accept
Strings (and you want to use Strings in the vector).
+ is not applicable for objects.

If you are not using java 1.5, but lower, you cannot use generics. In
that case you have to do a type cast:
for(int count=0;count<vectorSize;count++) {
 sum += (String)tokens.elementAt(count);
}
(Of course only if sum is a String...)

Think your code can be improved, too.
If you want to iterate over the vector, I think it is better not to use
an extra variable vectorSize, but use tokens.size() instead.
If you use java 1.5, you can also write: (if the vector contains only
Strings and you are using generics)
Vector<String> tokens = new Vector<String>();
tokens.add(...);
...
String sum="";
for (String s:tokens) {
 sum+=s;
}
Something like that.
Hope that helps!
bye, Ralf
Zaph0d - 07 Sep 2006 09:03 GMT
> String sum="";
> for (String s:tokens) {
>   sum+=s;
> }

Actually, it'll be much better using StringBuilder for this type of a
loop.

String is immutable. Meaning that String s += "1'; will actually create
a new String object and, eventually, gc the old one.
StringBuilder sb = new StringBuilder();
sb.append(s); sb.append("1");
will use the same buffer array (if possible).
Note1: that the buffer is using doubling strategy (if running out of
space, double the array size and copy the old array to the first half
of the new array), so it might be wise to specify initial size, if you
can.
Note2: StringBuilder is not synchronized. If you're multi-threading,
use StringBuffer (which is a tad slower).
Ralf Seitner - 07 Sep 2006 09:28 GMT
Zaph0d schrieb:
>> String sum="";
>> for (String s:tokens) {
[quoted text clipped - 3 lines]
> Actually, it'll be much better using StringBuilder for this type of a
> loop.
Hi!
You are right.
To be honest, I did not know, there is a StringBuilder. Saw it is new by
1.5 ;-) (Of course I know StringBuffer, which would have been an option,
too)
But there was one thing in my mind:
Had the feeling, the OP is relatively new to java, so I tried to make
the example as easy as possibly.
And... If it is not a String, this loop also works for Integer, etc.
But thanks. Learned something, too. :-)
> String is immutable. Meaning that String s += "1'; will actually create
> a new String object and, eventually, gc the old one.
[quoted text clipped - 7 lines]
> Note2: StringBuilder is not synchronized. If you're multi-threading,
> use StringBuffer (which is a tad slower).

bye, Ralf
Vera - 08 Sep 2006 15:59 GMT
My bad, I should've specified: sum is a double and the vector "tokens"
stores double values.

The full compiler message is: "operator + cannot be applied to
double,java.lang.Object"
Patricia Shanahan - 08 Sep 2006 16:29 GMT
> My bad, I should've specified: sum is a double and the vector "tokens"
> stores double values.
>
> The full compiler message is: "operator + cannot be applied to
> double,java.lang.Object"

No Java Vector can contain anything other than references to objects,
but autoboxing will do some automatic object creation which may be
confusing matters, making it look as though you can add a double.

How was tokens declared? How is it initialized?

Patricia
Vera - 08 Sep 2006 16:45 GMT
This is what I have:
--------------------------------------------------------------------
        Vector tokens = new Vector();

        try
        {
            // Start reading the file
            FileReader fr = new FileReader(file);
            BufferedReader inFile = new BufferedReader(fr);

            // Read the file till EOF
            while((line = inFile.readLine())!= null)
           {
                tokenizer = new StringTokenizer(line);

                   // Convert string to double format
                   Double lineD = Double.parseDouble(line);

                 // Print number
                 // System.out.println(lineD);

            // Store number in array
            tokens.add(lineD);
            }
----------------------------------------------------------------------------------
Patricia Shanahan - 08 Sep 2006 17:57 GMT
> This is what I have:
> --------------------------------------------------------------------
[quoted text clipped - 21 lines]
>             }
> ----------------------------------------------------------------------------------

tokens contains references to Double objects.

There are two paths from here to where you want to be. I'm going to
discuss the older path, rather than opening the generic and autoboxing
cans of worms.

The result of tokens.elementAt(count) is an expression of type Object,
referring to a Double object. You need to do two things to make it
something you can add, change the expression type from Object to Double
with a cast, and invoke a Double method to get the double value:

sum += ((Double)tokens.elementAt(count)).doubleValue();

Patricia
Vera - 08 Sep 2006 20:03 GMT
Thank you sooooo much! And a special thanks for explaining to me what
was wrong with my code and why you wrote yours the way you did. I'm
very new to this so I don't understand a lot of things, so thank you
for clearing this up for me :-)

> tokens contains references to Double objects.
>
[quoted text clipped - 10 lines]
>
> Patricia


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



©2008 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.