• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array problem

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have the following array:
int myArray = new int[]{1,4,3,9,2,8,9,6,0};
Could someone please tell me how I can eliminate say, the number 9?
Also given: String names[] = new String[]{"Ann","James","Vic","Ann","Rose","Bill"};
How can I remove "Ann" from the list, then sort the remaining names?
Sample codes would be very much appreciated.
TIA and best regards.
Nosa
 
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think a java.util.Vector will be more useful.
HTH,
- Manish
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right. Arrays are fixed-size. Once you create an array of a certain size, you can't make it bigger or smaller. All you can do is created a new one of a different size, and copy over the elements you want to keep from the old array.
In java.util, there are many Collections classes that allow you to dynamically change the size of your data structure. Look at ArrayList.
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And if you're not ready to explore Vectors or other Collections classes...
As Rob was saying, once created, an array's size cannot be changed. You can create a new array object of a different size, copy selected members from the original array into the new array, and then drop the reference to the original array and use your reference variable to refer to the new array (if you want to).
As for sorting, the Collections have built in sorting algorithms - but just using them will teach you nothing about how sorting algorithms work. If you want to learn about how different sorting algorithms work, just do a search on this forum for the word sort in the subject heading (the link is at the top right of this page). Also, a search on Google for words like sort, algorithm, java, etc. will produce many hits.
If you're having difficulties figuring out the details, just say so, many JavaRanchers would be glad to help.
Good Luck,
-Dirk Schreckmann
 
Nosa Irenen
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well thanks for your replies. But as Dirk mentioned, I'm having difficulties figuring out the details about using vectors.
Below is what I tried concocting. I'd appreciate you telling me how to make it work.

import java.util.Vector;
public class ArrayVal
{

Vector val = new Vector();
public void add(int i)
{
val.add(new Integer(i));
}


public int elementAt(int i)
{
return ((Integer)val.elementAt(i)).intValue();
}

public int elements(int i)
{
return (val.elements(i)); //CORRECT THIS
}

public void remove(int i)
{
val.remove(new Integer(i));

}

public static void main(String[] args)
{
ArrayVal v = new ArrayVal();
v.add(1);
v.add(3);
v.add(0);
v.add(4);
v.add(0);
v.add(5);
System.out.println(v.elementAt(2));
// how can I view the inserted elements?
// v.elements below doesn't seem to vork
System.out.println(v.elements); //???

}
}
TIA for your immense help.
Nosa
 
Nosa Irenen
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I also found that " v.remove(v.elementAt(2));"
removes the third element. Is there a neater way to do this? Also I know the position before hand. But what happens if I'm treating a large array, em... vector and I have no idea where the items I want to remove occur?
Please accompany your explanations with some code snippets. I'm beginning to lose my hair on this.
Thanks once again for your help.
- Nosa
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
Looking at the Vector class documentation in the Java 2 API Specification we have the indexOf(Object) and other useful methods. indexOf(Object) returns the position of the first occurance of the Object in the Vector. That's one way to find a given element.
Just a note about your index counting comment:
Were you surprised that the third element was actually at position number 2? So called "natural" programming languages count using the non-negative integer set. Non-negative integers are {0, 1, 2, 3, 4, etc.} - counting starts at the first number which is 0, the third one is 2, etc.
Good Luck,
-Dirk Schreckmann
[ March 09, 2002: Message edited by: Dirk Schreckmann ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also,
The removeElementAt(int) method deletes the component at the specified index.
 
Nosa Irenen
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you please explain how I can view all the elements of a vector? As I mentioned earlier I could not get the elements() method to work. I suppose either the syntax was wrong or there's another method.
Thanks.
- Nosa
 
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println(v.elements);

There are two things wrong. elements is a *method*, it should be v.elements()

Also, look at the API. the elements method returns an Enumeration. If you don't know about it, click the link to go to Enumeration.

Enumerations have a few methods as well. And wow... a code example that you could actually copy and paste into your code with no modifications and it would work.

And it looks like you are trying to make a "contain and delegate" class. So your own version of elements method takes as an argument and returns an integer. Not sure why you'd want that. You should have it mirror the API's method definition, *or* if you wanted it to be a convenience method which does the work for you, have it return void, and paste the above mentioned code from the API into this method.
 
Nosa Irenen
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to thank you all for your input. I took a peek at the relevant documentation and here's what I managed:
/*
Create Vector of integers (9,4,3,5,9,2,7,6,1)
loop thru elements and remove occurences of the nines
*/
import java.util.*;
public class remVector
{
public static void main(String[] args)
{
Vector v = new Vector();
// to store a primitive datatype within a vector
// we use wrapper classes as found in java.lang package
v.add(new Integer(9));
v.add(new Integer(4));
v.add(new Integer(3));
v.add(new Integer(5));
v.add(new Integer(9));
v.add(new Integer(2));
v.add(new Integer(7));
v.add(new Integer(6));
v.add(new Integer(1));

System.out.println(v);

// to remove the nines
// we loop through values to identify the nines:
for (int i = 0; i < v.size() ; i++)
{
// chk that index value is a nine
if (v.contains(new Integer(9))) {
v.remove(new Integer(9));
}
}

System.out.println("Now we remove the nines...");

// then we print the remaining:
System.out.println(v);

}

}
In what ways can I improve on this?
TIA
- Nosa
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

A couple of notes:
When constructing the Vector, if you already know how many elements it is going to have, go ahead and tell it how big it needs to be. That way it doesn't have to change its capacity when it's capacity has been reached. For such a small Vector, this isn't going to make much difference. Your original Vector was initially created with a size of 10 and its size would have been incremented by 10 whenever its capacity had been reached and a new element was added. By initially creating it with its known-to-be-needed-capacity, it doesn't spend time resizing. (So, maybe this saved 0.0002 milliseconds here.)
The neat part of using a Collection is all of the methods available for operating on them. We often don't have to manually step through the elements checking for this or that (as we maybe need to with a "normal" array of elements - int[]) - often a method is available to do this for us. Here I've given two examples of ways to remove all occurances of a given element without having to manually step through the Vector's elements and perform a check for equality at each element.
Explore The Java 2 API Specification. It's filled with great information on how things work and what's available for use.
Good Luck.
[ March 11, 2002: Message edited by: Dirk Schreckmann ]
 
Nosa Irenen
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Many thanks to you Dirk.
Between your explanations and what I've read so far, my understanding of Arrays and Vectors has been considerable.
I hope to be able to help others myself in the future.
Regards.
- Nosa
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's the spirit.
And if you don't know the answer to a question, just make something up and post some code.
Or, you could follow the style of post-padding by just copying what someone already advised and posting it into a new response. Marilyn and Rob are recent practitioners of this in:
overloaded methods in derived class
and
How to convert a string to a float or double?
Note: this is a lot easier to get away with if your copied advice is posted only a couple of minutes after the initial advice posting. That way you could at least claim, "Hey, these threads aren't synchronized! We must have posted at the same time." This is my preferred style.
If you are ever having troubles getting adequate responses, just reregister with a name like Jennifer, Sarah, Heather, etc. These names seem to be draw JavaRanchers to respond by the dozen.
Now, whatever you do, don't ever hijack a thread.
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If you are ever having troubles getting adequate responses, just reregister with a name like Jennifer, Sarah, Heather, etc. These names seem to be draw JavaRanchers to respond by the dozen.


HAHAHAHAHAHAHAHAHAHAHAHA
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone post what the code would have been if she would have used an array, instead of a vector? I want to see the comparison. With the array would you have to use the bubbleSort to move the items to the end and then only print the remaining? Or is their an easier way?
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"lilnaniam",
Welcome to the JavaRanch.

We're a friendly group, but we do require members to have valid display names.

Display names must be two words: your first name, a space, then your last name. Fictitious names are not allowed.

Please edit your profile and correct your display name since accounts with invalid display names get deleted, often without warning

thanks,
Dave
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ranchers,


welcome to the ranch, lilnan!

lilnaniam (who's name may change in the next days with some probability)
posted November 13, 2006 11:13 PM

Can someone post what the code would have been if she would have used an array, instead of a vector? I want to see the comparison.


For the sorting, there are the utility methods .sort(..)
in the java.util.Arrays and java.util.Collections classes. These methods are static.
Arrays.toString(an_array) is a method to print out arrays.


There is also an automatic possibility of copying arrays into a Vector (or any other List as e.g. ArrayList). But this will leave the array and the list tied together.
See for java.util.Arrays.asList for details.

Please use this button:

Yours,
Bu.
 
Shananne DuFrame
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've gotten alot more understanding of vectors vs. arrays. I tried this program to try to see if it would delete the searched integer and location withing the array. For deleting a specific interer in the array I thought I was going to have to create a new array. But now in the program I've created It doesn't delete all instances of the searched integer, only the first. Like if I put all one's in it only deletes the first one. Anotherproblem I'm having is with creating an empty array. I don't want it to accept 0's as a value nor print them. I've been working and reading on forums all night to get as far as I have. Any help would be greatly appreciated.

And yes, lol, changed my profile name right away :-)

Heres my code:
 
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was baffled as to why Vector was still being suggested in this day and age. Then I realized that this thread is over four years old. Shananne if you have a question it might be more appropriate to create a thread and ask rather than reviving and hijacking a four year old thread.
 
Shananne DuFrame
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was only looking for something comparable to what I'm learning. I'm a student and right now we are on list processing. In the book it is teaching us with vectors, but we are doing assignments in arrays. Which makes the task a little bit more difficult beings we are being shown with vectors. Just out of curiosity why is it that vectors are out dated, seems from what I've been reading on forums and such that using a vector would have been much easier. What is the advantage/disadvantage to using an array over using a vector? Seems everthing I've been reading points to vectors more.(Possible everything I've been reading is outdated too :-)..)None of the forums I've read have come close to containing info pertaining to info I was looking for with arrays. Any suggestions to updated info would be appreciated, also. I guess in the future I'm better off not to compare to old posts? Post new threads? Sorry for any confusion.
 
Shananne DuFrame
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I did find this on another post in here about vectors:

One reason for not using Vector is that it is internally synchronised. This may sound good initially, but in fact that synchronisation reduces performance in all applications, while very rarely achieving true thread safety in multi-threaded applications.

Same applies to Hashtable.

If an experienced Java hacker sees you using Vector or Hashtable in new code, they are likely to think badly of you, so don't do it!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic