• Post Reply Bookmark Topic Watch Topic
  • New Topic

Subtracting in Vectors - Please Help!  RSS feed

 
Naf Rash
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to look at two elements at certain indexes from two different Vectors and then subtract them from one another. Is this possible to do? I have tried applying the - operator directly to vectors but I am getting an error saying that it is not allowed. Is there a way around this?
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Naf Rash:
I want to look at two elements at certain indexes from two different Vectors and then subtract them from one another. Is this possible to do? I have tried applying the - operator directly to vectors but I am getting an error saying that it is not allowed. Is there a way around this?

To do much with Vectors, the first thing you have to do is cast the objects stored in them to the appropriate class. For example, if you have 2 Vectors that both contain Integer objects, then you can do something like this:

Does that help?
 
Naf Rash
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes thanks that helped! Just 1 more thing though - The vectors store various different types fo elements ie, of type String, int etc.... Therefore, when an attempt to carry out the subtraction occurrs would I be correct in assuming that a NumberFormatException occurrs?
 
Geoffrey Falk
Ranch Hand
Posts: 171
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you would get a ClassCastException (for instance, trying to cast a String to an Integer).
Geoffrey
 
Naf Rash
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I used the code provided earlier but for some reason it doesn't like the line:
Integer integerObject1 = (Integer)((Vector)row.get(i)).get(i1);
This compiles properly but doesn't run ie, a run-time error is produced. I have adapted the code that was originally posted because I am using a vector of vectors and thus trying to access the inner 1st element. For purposes of keeping this simple even using the code as it was originally posted produces the same run time error - any idea why?
I've inserted the following line and this works - so why doesn't the above?


System.out.println("check somet in the vector 2 " + ((Vector)row.get(1)).get(1))
[ March 16, 2004: Message edited by: Naf Rash ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!