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 / March 2008

Tip: Looking for answers? Try searching our database.

Vector class

Thread view: 
HelpMe - 08 Mar 2008 04:54 GMT
I have implemented a vector class.It's fine except it shows the
element at position 2 i.e. index 1 is 19 even after removing it.But
the size i am able to decrease.What should I do for that? Can anyone
suggest me?My program is:-

import java.io.*;

class VectorEmptyException extends RuntimeException {
     VectorEmptyException(String message) {
     super(message);
 }

}

class Vector<T> {
     Object[] data;
     int count;

  Vector() {
     data = new Object[1];
     count = 0;

}

  Vector(int s) {
     data = new Object[s];
     count = 0;

}

  int size() {return count;}

  Object elementAt(int i) throws VectorEmptyException {
         if(i>=count) throw new VectorEmptyException("Vector is
empty");
         return data[i];
         }

  void add(int index,Object O) {
        if(data.length == count) {
          Object[] newdata = new Object[data.length*2];
        for(int i=0;i<count;i++) {
            newdata[i] = data[i];
          }
         data = newdata;
}

         for(int i=count;i>index;i--) {
            data[i] =data[i-1];
         }
         data[index] = O;
         count++;

}
 Object remove(int index) throws VectorEmptyException{
          if(index >= count) throw new VectorEmptyException("Vector
is empty");
          if (data.length <= count) {
          Object[] newdata = new Object[data.length-1];
             for(int i=0;i<index;i++)
             newdata[i] = data[i];
             for(int i=index;i<count-1;i++)
             newdata[i] = data[i+1];
             data = newdata;}
             count--;
             return data[index];

}
    public static void main(String[] args){
        Vector<Integer> v = new Vector<Integer>();
        try{
         v.add(0,22);v.add(1,19);v.add(2,45)
         System.out.println("The 2nd element is : " +v.elementAt(1));
         System.out.println("The size of the vector is : "
+v.size());

         System.out.println("The removed element is : "
+v.remove(1));
         System.out.println("The 2nd element is : " +v.elementAt(1));

         System.out.println("The size of the vector is : "
+v.size());
         }
         catch(VectorEmptyException e){
         System.out.println("The vector is empty");
         System.out.println(e.getMessage());
        }
  }
}
Peter Duniho - 08 Mar 2008 06:23 GMT
> I have implemented a vector class.It's fine except it shows the
> element at position 2 i.e. index 1 is 19 even after removing it.But
> the size i am able to decrease.What should I do for that? Can anyone
> suggest me?My program is:-

Well, aside from a variety of other things that make the code you posted  
questionable (not the least of which is the question as to why you'd  
bother to implement a vector class, given that Java already has perfectly  
good dynamic collections...smells like homework to me), I'd say the most  
significant thing is that your "remove()" method will only do something if  
the array holding your data has a length equal to or less than the number  
of elements being held.

That length can never be less than, and it will only be equal to when the  
capacity of your vector is exactly the same as the number of elements  
being held in it.  After you've added three elements, that's not the  
case.  So your "remove()" method doesn't do anything when you call it.

For what it's worth, you would have seen this immediately yourself had you  
just bothered to step through the code in a debugger.

Pete
Hendrik Maryns - 10 Mar 2008 09:55 GMT
HelpMe schreef:
> I have implemented a vector class.

Why?  java.util.Vector and java.util.ArrayList work just fine (use the
latter if you don’t know why you should use the former).

It's fine except it shows the
> element at position 2 i.e. index 1 is 19 even after removing it.But
> the size i am able to decrease.What should I do for that? Can anyone
[quoted text clipped - 11 lines]
> class Vector<T> {
>       Object[] data;

Make that T[]

>       int count;

I’d simply initialize count where you declare it:
in count = 0;

>    Vector() {
>       data = new Object[1];
>       count = 0;

and remove these two lines with count = 0;

> }
>
[quoted text clipped - 9 lines]
>           if(i>=count) throw new VectorEmptyException("Vector is
> empty");

You throw an exception indicating the vector is empty when someone
retrieves an element at a wrong index?

>           return data[i];
>           }
[quoted text clipped - 5 lines]
>              newdata[i] = data[i];
>            }

Use System.arrayCopy

>           data = newdata;
> }
[quoted text clipped - 9 lines]
>            if(index >= count) throw new VectorEmptyException("Vector
> is empty");

Again?

>            if (data.length <= count) {

As peter pointed out, s/count/index/

>            Object[] newdata = new Object[data.length-1];
>               for(int i=0;i<index;i++)
>               newdata[i] = data[i];
>               for(int i=index;i<count-1;i++)
>               newdata[i] = data[i+1];
>               data = newdata;}

Your {} are in the wrong place.  This amounts to what Peter said.
Do you want to copy the whole array each time an element is removed?
This means if you add an element after removing one, you’ll have to copy
the whole array again!  (Since it won’t fit.)  Just keep some null
elements at the end.

>               count--;
>               return data[index];

I think it’s bad practice to return a value from a method that changes
things.  Functions (returning a value, without side effects) and
procedures (changing stuff, no return value) should be kept separated
where possible.

H.
Signature

Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Lew - 10 Mar 2008 14:01 GMT
> Why?  java.util.Vector and java.util.ArrayList work just fine (use the
> latter if you don’t know why you should use the former).

The only reason to use Vector is to support certain classes that never were
retrofitted with the Collections framework.  For any original work there is a
better alternative available.

Signature

Lew

Lew - 10 Mar 2008 14:02 GMT
HelpMe schreef:
>>       int count;

> I’d simply initialize count where you declare it:
> int count = 0;
[quoted text clipped - 4 lines]
>
> and remove these two lines with count = 0;

Better yet, observe that instance variables are initialized to 0 for you, and
leave the "= 0" out altogether.

Signature

Lew

Lew - 10 Mar 2008 14:04 GMT
HelpMe schreef:
>>    void add(int index,Object O) {
>>          if(data.length == count) {
>>            Object[] newdata = new Object[data.length*2];
>>          for(int i=0;i<count;i++) {
>>              newdata[i] = data[i];
>>            }

> Use System.arrayCopy

Or Arrays.copyOf():
<http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf(T[],%20int)>

Signature

Lew



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.