Understanding vectors

I do not quite understand vectors regardless of how many pages I read on them, I have been assigned this program in my java class, I have written the following code so far, some of it was given to me, such as the v.add(cr) in the student class, however I have no clue as to what exactly is in my vector, where it is, and how to pull the variables that I need from it, which is what I ultimately need to do. If someone could please shed some light and point me in the right direction I would appreciate it. I have three classes, gradebook(supplies a gui with 3 buttons, one of which adds a student who has characteristics and up to 5 courses, one button which is supposed to print everything about the students(which is nowhere near done yet, don't worry about that), and one just to exit. Here's my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Gradebook extends JFrame
private Button add;
private Button print;
private Button exit;
float[] gpa_array=new float[5];
private int num_students=0;
Student[] stu=new Student[5];
public Gradebook()
super("Student/Course GUI");
for(int a=0;a<5;a++)
stu[a]=new Student();
ButtonHandler handler = new ButtonHandler();
Container cat = getContentPane();
cat.setLayout(new FlowLayout());
add = new Button("Add Student");
add.addActionListener(handler);
cat.add(add);
print = new Button("Print");
print.addActionListener(handler);
cat.add(print);
exit = new Button("Exit");
exit.addActionListener(handler);
cat.add(exit);
setSize(800,600);
setVisible(true);
public class ButtonHandler implements ActionListener
public void actionPerformed(ActionEvent e)
if(e.getSource()== add)
num_students++;
stu[num_students].getData();
else
if(e.getSource() == print)
System.out.println("Printing all courses and students");
else
if(e.getSource() == exit)
System.exit(0);
public static void main(String[] args)
Gradebook app = new Gradebook();
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Vector;
public class Student
private String name;
private String stringage;
private int age;
private float gpa;
private int num_courses;
private String stringnum_courses;
private int totalqp;
private Vector v = new Vector();
    public Student()
public void getData()
name = JOptionPane.showInputDialog(null,"Enter Student's Name","Enter Student's Name", JOptionPane.QUESTION_MESSAGE);
stringage = JOptionPane.showInputDialog(null,"Enter Student's Age","Enter Student's Age", JOptionPane.QUESTION_MESSAGE);
age = Integer.parseInt(stringage);
stringnum_courses = JOptionPane.showInputDialog(null,"Enter Number of Courses","Enter Number of Courses", JOptionPane.QUESTION_MESSAGE);
num_courses = Integer.parseInt(stringnum_courses);   
for(int a=0;a<num_courses;a++)
Course cr = new Course();
v.add(cr);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Course
    // instance variables - replace the example below with your own
    private int id;
    private String dept;
    private int credits;
    private String letter_grade;
    private String stringid;
    private String stringcredits;
    private int QP;
    public Course()
     getDept();
     getId();
     getCredits();
     getLettergrade();
     getQP();
    public void getDept()
       dept = JOptionPane.showInputDialog(null,"Enter Department","Enter Department", JOptionPane.QUESTION_MESSAGE);
public void getId()
stringid = JOptionPane.showInputDialog(null,"Enter Course ID","Enter Course ID", JOptionPane.QUESTION_MESSAGE);
id = Integer.parseInt(stringid);
public void getCredits()
stringcredits = JOptionPane.showInputDialog(null,"Enter Credits","Enter Credits", JOptionPane.QUESTION_MESSAGE);
credits = Integer.parseInt(stringcredits);
public void getLettergrade()
letter_grade = JOptionPane.showInputDialog(null,"Enter Letter Grade","Enter Letter Grade", JOptionPane.QUESTION_MESSAGE);
public void getQP()
if(letter_grade=="A")
QP=4*credits;
if(letter_grade=="B")
QP=3*credits;
if(letter_grade=="C")
QP=2*credits;
if(letter_grade=="D")
QP=credits;
if(letter_grade=="F")
QP=0;
}Here is the exact assignment just for any clarification purposes:
3 classes
Course
Student
Gradebook(main)
The Main class will have 3 Buttons to control the following Events:
1...Add student to system (initial data--name, gender, and course load (1 to
5 courses))
A Vector in the student class will be initially set to 5 courses for
each of 5 possible students
An array in the Gradebook class will hold references to each of the 5
student objects
2...Print all student data (along with gpa) High to low based upon gpa.
3...Exit

Hi could i solve your problem, how ever i understand you have a problem that what is stored in your vector and how to get from it... let me explain may you know it.
well
for(int a=0;a<5;a++)
stu[a]=new Student();
if(e.getSource()== add)
num_students++;
stu[num_students].getData(); ///specified student object
for(int a=0;a<num_courses;a++)
Course cr = new Course();
v.add(cr);
you are adding courses in the vector in the specified student object
well other method of vector could be vector.addElement();
'add' and 'addElement ' add an object type thing one after another....
so your ' v ' vector object will contain courses object when you will get them you need to do type cast for example you have to do same for print button what you have done for add button but only here you will getting things.
you will do below code in the student class by making new method ...
if( v != null && v.size > 0)
Courses objCourse = (Courses) v.elementAt(0);
you can get all courses object by looping them to the size of the vector
i hope this will work for what ever i understand your problem.
Cheers
ABId

Similar Messages

  • Understanding vector art

    If I need to use some vector clip art, but I have to guarantee that's it 100 percent grayscale with no color, I understand that I should open it in Illustrator and change it to grayscale. That's the safest option, right?
    I work with a designer who chooses to use Photoshop for the same mission. He opens the vector art in Photoshop, changes it to grayscale and then sizes it to the way he wants.
    If I use Illustrator to work with vector art, the advantage is that the art stays a true vector image, right?
    If my designer uses Photoshop, that means that he is rasterizing (bitmapping) the vector image and once he re-sizes it, that's the size it will be.
    Am I right on this?

    I would say Scott makes the point very well Illy to Photoshop is if you need to bring Illy art to be used with photoshop fie because it is better to create that kind of art in AI.
    Also I do not see why you would have to resize in Photoshop you can export to psd format and choose your options at export time such as resolution.

  • Understanding Vector Smart Objects in PSD

    I'm trying to learn to use Smart Objects in PS to edit files created in AI. I watched the Adobe TV video as well as a few others. It seems easy as pie. But one thing confuses me. What is the file that gets created called  Vector Smart Object.ai? Do I need to do anything with it? Does it et saved anywhere? I don't see it in the folder in which I've stored my psd and ai file. It just seems to go away when I close everything down. BTW- I'm in cs 6 and am using Place command. Many thanks for helping me to understand this.

    If I am in CS 6, then are you saying I can currently delete the ai file and still be ok - that that is how CS6 & Embedding works?
    Yes. You can easily verify this. Move the used AI file to another location via Explorer/Finder so Photoshop won't find it. Open your PSD file and you will see that Photoshop opens the file just fine because there is no connection any more with the original file.
    And if so - what are the benefits of the Linking compared to the current Embedding - now available in CC? - again - many thanks!
    Say you use the same logo made in Illustrator on many different projects e.g. a letter head, a poster, a business card, whatever. Now your client says: I like all the different layouts but I think I would prefer green text instead of blue text... No problem at all for you, you change it once in the AI file and it will update automatically in all the linked objects.
    Obviously in that case, the AI file can not be deleted or moved or Photoshop (and you) will have a heart attack...

  • Vector renewed but memory not released

    Hi,
    Please see the following code:
    Vector v = new Vector(10000000);
    // from windows task manager, it seems it takes 40 Mb of memory.
    // there is a need to do the following after some code
    v = new Vector(10000000);
    // now the memory taken is around 80 Mb
    It would be useful if the program releases the earlier memory of 40 Mb. May be it does not work that way? Any thoughts are welcome.
    Regards
    Chandra.

    Thank you all folks. Each suggestion helps me understand vectors and memory in a better way than before. I have noted setting the heap and also the 'clear' function.
    When I repeat the code several times, it seems that initially there is an increase in memory up to a certain limit (in my case it is 128 Mb) but there is no increase after that, how many times I repeat the code. (Repeating the code is to find when the out of memory problem occurs). It works okay for now.
    Thanks to all again.
    Regards
    Chandra.

  • Vector vs bitmap, gradient/transparency/filter performance questions on ios

    so i understand vector artwork is all done by cpu and drawn every frame and bitmaps can be loaded directly from ram using the gpu but when you have simple objects such a masks and static lines, is it more efficient to use vector graphics for a mask? or should it be a bitmap?   what about a line, since it is just a graphic made using a equation rather then wasting resources on a large picture?
    also when movieclips have filters on them such as bluring, it seems like it overlays multiple transparent copies of the image onto the selected movieclip. Does the cpu then have to multiply each colour of the transparent images to arive at the final blur? when i cache this as a bitmap and the edges are feathered/transparent does the gpu multiply the transparercies at the edges? or is it still the cpu that handles it?
    I also wanted to know how stressing gradients are on the cpu/gpu, as a bitmap i assume it is treated the same as any other image but as a vector is it more costley on the cpu to have it up on the stage than an image?
    if there is any tips for graphics on mobile devices i would love to hear them.

    so i understand vector artwork is all done by cpu and drawn every frame and bitmaps can be loaded directly from ram using the gpu but when you have simple objects such a masks and static lines, is it more efficient to use vector graphics for a mask? or should it be a bitmap?   what about a line, since it is just a graphic made using a equation rather then wasting resources on a large picture?
    also when movieclips have filters on them such as bluring, it seems like it overlays multiple transparent copies of the image onto the selected movieclip. Does the cpu then have to multiply each colour of the transparent images to arive at the final blur? when i cache this as a bitmap and the edges are feathered/transparent does the gpu multiply the transparercies at the edges? or is it still the cpu that handles it?
    I also wanted to know how stressing gradients are on the cpu/gpu, as a bitmap i assume it is treated the same as any other image but as a vector is it more costley on the cpu to have it up on the stage than an image?
    if there is any tips for graphics on mobile devices i would love to hear them.

  • Vector vs bitmap, transparency & gradient on ios

    so i understand vector artwork is all done by cpu and drawn every frame and bitmaps can be loaded directly from ram using the gpu but when you have simple objects such a masks and static lines, is it more efficient to use vector graphics for a mask? or should it be a bitmap?   what about a line, since it is just a graphic made using a equation rather then wasting resources on a large picture?
    also when movieclips have filters on them such as bluring, it seems like it overlays multiple transparent copies of the image onto the selected movieclip. Does the cpu then have to multiply each colour of the transparent images to arive at the final blur? when i cache this as a bitmap and the edges are feathered/transparent does the gpu multiply the transparercies at the edges? or is it still the cpu that handles it?
    I also wanted to know how stressing gradients are on the cpu/gpu, as a bitmap i assume it is treated the same as any other image but as a vector is it more costley on the cpu to have it up on the stage than an image?
    if there is any tips for graphics on mobile devices i would love to hear them.

    When you put the images in a vector slideshow overlay you change the display experience. You'll see a low-res version of each image show up first, then the high-res version snap in. Many publishers don't like that experience. You make the overal folio side larger too, as we have to embed both the full-size image and the lower-quality thumbnail images.
    Unless you are creating a single edition application you should publish two renditions, one SD and one HD. Create your designs as 1024x768 InDesign documents and place images in your slideshows that are large enough to be nice on a retina ipad. Use a raster slideshow.
    Then use that source InDesign document to create articles in two folios: one at 1024x768 and one at 2048x1536. We'll be smart and scale the images in the slideshow based on the size of the folio. If you have a sidecar.xml file the work to create the second rendition in Folio Builder Panel is very fast. You can create an empty 2048x1536 PDF folio and import all the finished InDesign articles at once.
    Publish both folios and you're done. Beautiful content on SD, beautiful content on HD.
    Neil

  • FW CS3 problem with Vector Images PLEASE HELP

    Hello,
    My name is Logan and I work for a company called Sutherland
    Design Agency. I am creating a website and i created some vector
    images in illustrator for the logo because i wanted source files to
    be imported into fireworks. When I imported the ai file it seemed
    to be rasterized. Is this normal?
    I would like my images to stay as vectors in fireworks so i
    decided to test this a couple times. When i create a vector i save
    it and import it into fireworks. It's a raster. Then i export it as
    an illustrator file and when i open it, it's a vector again. So i
    know that it is a vector, but why won't it show up in fireworks
    CS3.
    I also noticed the drop-down bar with the different image
    types. Is fireworks auto-optimizing? If so, is there a way to turn
    this off? I want to do my own optimization and I want to view the
    fireworks document the way it is.
    Much help would be greatly appreciated.
    Thanks,
    Logan
    Sutherland Design Agency

    Anagon wrote:
    > okay i'll try that and post my result here.
    >
    >
    FW CS3 should import your AI file without downsaving it to AI
    8. Keep in
    mind though, FW always displays vectors as they would appear
    when
    exported as bitmaps (browsers don't understand vector files
    without a
    helper application). If you are zooming in (not scaling) on
    the canvas,
    the artwork will start to look pixelated, because the stroke
    and fills
    are being displayed as bitmaps. Scaling the image should have
    no
    detrimental effect on the vector.
    Jim Babbage - .:Community MX:. & .:Adobe Community
    Expert:.
    http://www.communityMX.com/
    CommunityMX - Free Resources:
    http://www.communitymx.com/free.cfm
    .:Adobe Community Expert for Fireworks:.
    Adobe Community Expert
    http://tinyurl.com/2a7dyp
    See my work on Flickr
    http://www.flickr.com/photos/jim_babbage/

  • Storing a lot of data in an indexed data structure for quick access.

    I'm designing an app. which will need to store a large amount of data in memory. Records will be flowing into the app. via a socket. The app will receive about 30 records/second which is about 108,000 records/hour and about 600,000 records/day. I need to store the records in an indexed data structure so that I can access them quickly. For example, at 9:00am I will need to access records received at 8:30am, 8:35am, 8:40am, etc. This program will be multithreaded and as I understand Vector is the only data structure that is thread safe. Is Vector my only choice? How do I access objects in a Vector using an index? Is there something better that I can use?

    Is Vector my only choice?If you want to access the objects by key then you should use something like a HashMap. But if you want to access them by an array index then an ArrayList would be more appropriate.
    as I understand Vector is the only data structure that is thread safeYou can get a thread-safe version of any Collection object by using the Collection.synchronizedCollection method.
    How do I access objects in a Vector using an index? I'd suggest you read the API documentation. And probably the Sun tutorial on Collections at http://java.sun.com/docs/books/tutorial/collections/index.html
    600,000 records/day. Unless you plan to dump old data after a short period of time, you may want to consider using a database to avoid running out of memory.

  • Help with Logo

    I'm looking for some help in a corporate logo.
    The logo is fairly simple, mainly using letters and a couple vector circles.  I am new to this so any help/beginner advice would be appreciated on the following:
    - I need to try to 'erase' a small part of one letter in the logo.  When I select the eraser it won't allow me to erase this small piece of the letter without rasterizing the letter first.  Is there a way to erase this small piece of letter without rasterizing it?
    - If I build all of the letters and the small circles as vectors, and save the image as an .eps, will I be able to adjust the size of the logo overtop of images without having to worry about image quality (will it re-scale as an .eps automatically?)
    If you can help provide me with some beginner advice it would be much appreciated!  Thanks.  I'm trying to better understand vector images and .eps files.

    smackitsakic258 wrote:
     ...without rasterizing it?...
    You're looking at the wrong software. Photoshop is primarily a raster image editor.
    Logos are more easily designed in a primarily vector program like Illustrator. If you don't have Illustrator, try vector editors like Inkscape or Expression for free (or get the 30-day trial of Illustrator).

  • Incredibly dumb and easy question

    Be gentle, I'm entirely new to AI and the vector world.
    I'm using CS5, if I open a new document (for print), and simple click the "T" (for text), and enter some text on the artboard, is this vector?
    I know I need to save it in AI, or EPS format, but I just want to confirm that creating vector words is this easy....?
    Thanks for any confirmation of my stupidity.

    Yes, I do understand vector....
    Raster is just dots, or pixels...that can blur when enlarged (pixelation)...
    Vector is really just a set of computer instructions that draw the requested shape, etc...
    I associate this to some degree with MIDI music - MIDI isn't like an MP3 that has the actual music in the file, instead the MIDI file is a set of instructions to play a certain instrument in a certain key, etc....not sure if this is a good analogy or not....but it makes sense to me...
    I guess I'm not stupid, just completely new to AI...but I aim to change all that ;-)
    Thanks!

  • Can someone recommend good settings for HC Encoder?

    Hi all,
    I have an SD, 25p 16:9 movie that I wish to encode for burning to DVD.  Now, it is an .avi that was made with Avisynth.  I wish to know what settings you recommend while using HC Encoder.  I just want to minimize loss of quality and be able to put the .m2v into Encore.
    I have searched the web many times trying to find this answer but there seems to be little documentation/tutorials for this encoder.
    I would appreciate any help with this.  Thanks!

    Hi,
    the language used is not important. Ideally it would be explained in a language independent way :)
    What's most important is that I get to understand beyond just cutting and pasting. I understand vectors and trigonometry and basic algebra and a little physics so a book that would assume a person is rusty in these areas would be great. hmm maybe I need to buy some school text books!!!!
    I found the following books below if someone has read one and can help me decide which to buy that would be great. Otherwise I'll have to buy all 4!
    martin
    [Beginning Math and Physics for Game Programmers|http://www.amazon.co.uk/Beginning-Physics-Programmers-Riders-Games/dp/0735713901/ref=pd_sim_b_9]
    [Physics for Game Developers|http://www.amazon.co.uk/Physics-Game-Developers-David-Bourg/dp/0596000065/ref=pd_sim_b_5]
    [Physics for Game Programmers|http://www.amazon.co.uk/Physics-Game-Programmers-Grant-Palmer/dp/159059472X/ref=pd_sim_b_4]
    [Mathematics and Physics for Programmers|http://www.amazon.co.uk/Mathematics-Physics-Programmers-Charles-Development/dp/1584503300/ref=pd_sim_b_5]

  • How to understand the Vector source code for function elements()?

    hello all:
    This following code snippet is extracted from java.util.Vector source code.
    who can tell me how i can understand what the function nextElement does?
    thank you
    public Enumeration elements() {
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < this.num_elem;
             public Object nextElement() {
              synchronized (Vector.this) {   //???
                  if (count < elementCount) {//???
                   return elementData[count++];
              throw new NoSuchElementException("Vector Enumeration");
        }

    Perhaps code would help more. This codeimport java.util.Vector;
    import java.util.Enumeration;
    import java.util.Iterator;
    public class Test {
        public static void main(String[] arghs) {
         Vector v = new Vector();
         Integer two = new Integer(2);
         // Fill the Vector
         v.add("One");
         v.add(two);
         v.add(new StringBuffer("Three"));
         // Enumerate through the objects in the vector
         System.out.println("---- Enumeration ----");
         Enumeration e = v.elements();
         while (e.hasMoreElements()) System.out.println(e.nextElement());
         // Loop through the objects in the vector
         System.out.println("---- Loop ----");
         for (int i=0; i<v.size(); i++) System.out.println(v.get(i));
         // Iterate through the objects in the vector
         System.out.println("---- Iterator ----");
         Iterator i = v.iterator();
         while (i.hasNext()) System.out.println(i.next());
    }produces this output
    ---- Enumeration ----
    One
    2
    Three
    ---- Loop ----
    One
    2
    Three
    ---- Iterator ----
    One
    2
    Three
    So, for a Vector, all three do the same thing. However, Iterator is part of the Collection Framework (see [url http://java.sun.com/j2se/1.4.2/docs/guide/collections/index.html]here). This allows you to treat a whole bunch of [url http://java.sun.com/j2se/1.4.2/docs/guide/collections/reference.html]objects which implement the Collection interface all the same way. I know this is way more than you were asking, but I hope it at least clears up what you were asking.

  • How to sort a object vector by its integer item ?

    hi everybody,
    [there were few topics on this in the forum, but nothing could solve my problem yet. so, please instruct me]
    I have to sort a vector which contains objects, where each object represents, different data types of values,
    ex: {obj1, obj2, obj3, ....}
    obj1---->{String name, int ID, String[] departments}
    i have to sort this vector at three times, once by name, then by ID and then by departments.
    Leaving name and department , first i want to sort the ID of each object and then re-arrange the order of objects in the array according to new order.
    what i did was, copied the vector all objects' ID values to an integer array then i sorted it using selection sort. but now i want to re-arrange the vector, but i still can't. please guide.
    here is the sort i did, and the
    int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i < ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    //*****here is where i need to re-arrange the entire vector by ID.
    I do understand this is some sort of database sort type of a question. but there's no database. it's simply i just want to sort the vector.
    Thank you.

    hi camickr,
    thank you for the detailed reply. but i still don't understand somethings. i tried to read the API and look for the collections.
    i have ObjectStore_initialData class (similar to person class), so do i still have to do a comparable class out of this class ? please simplify that.
    public class ObjectStore_initialData
         String NAME;
         int ID;
         String[] DPART;     
         public ObjectStore_initialData(String name, int id, String[] departments)
              NAME=name;
              ID=id;
              DPART = departments;
    public String getName()//----
              return NAME;
    public String getID()//----
              return ID;
    public String getDpart()//----
              return DPART;
    /*next class is the interface to collect the values from the user and put all of them at once in a vector*/
    //this class is to sort the vector by ID
    public class sorter
       public sorter()
       public static void sortbyID(Vector mintomaxID)
             int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i >< ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    //*****here is where i need to re-arrange the entire vector by ID.
    /*new comparable class */
    public class ObjectStore_initialData implements Comparable
         String NAME;
         int ID;
         String[] DPART;     
         public ObjectStore_initialData(String name, int id, String[] departments)
              NAME=name;
              ID=id;
              DPART = departments;
    public String getName()//----
              return NAME;
    public String getID()//----
              return ID;
    public String getDpart()//----
              return DPART;
    static class IDComparator implements Comparator
              public int compare(Object o1, Object o2)
                   ObjectStore_initialData p1 = (ObjectStore_initialData )o1;
                   ObjectStore_initialData p2 = (ObjectStore_initialData )o2;
                   return p1.getID() - p2.getID();
    /*how can i put the vector here to sort? */
    public sorter()
    public static void sortbyID(Vector mintomaxID)
    int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID[i]);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i >< ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    /* using collections to sort*/
    Collections.sort(mintomaxID, new IDComparator());
    and to check the new order i wanted to print the vector to command line.
    still it doesn't do anything.
    the url you mentioned is good as i see. but how can i implement that in my class ? please instruct and simplify. i know i just repeated the code, i didn't understand to do a comparable class in collections for this class. Please explain where i'm head to and where's my misleading point here.
    Thank you.
    Message was edited by:
    ArchiEnger.711

  • How to sort a Vector that stores a particular object type, by an attribute?

    Hi guys,
    i need help on this problem that i'm having. i have a vector that stores a particular object type, and i would like to sort the elements in that vector alphabetically, by comparing the attribute contained in that element. here's the code:
    Class that creates the object
    public class Patient {
    private String patientName, nameOfParent, phoneNumber;
    private GregorianCalendar dateOfBirth;
    private char sex;
    private MedicalHistory medHistory;
    public Patient (String patientName, String nameOfParent, String phoneNumber, GregorianCalendar dateOfBirth, char sex) {
    this.patientName = patientName;
    this.nameOfParent = nameOfParent;
    this.phoneNumber = phoneNumber;
    this.dateOfBirth = dateOfBirth;
    this.sex = sex;
    this.medHistory = new MedicalHistory();
    Class that creates the Vector.
    public class PatientDatabase {
    private Vector <Patient> patientDB = new Vector <Patient> ();
    private DateFunction date = new DateFunction();
    public PatientDatabase () throws IOException{
    String textLine;
    BufferedReader console = new BufferedReader(new FileReader("patient.txt"));
    while ((textLine = console.readLine()) != null) {
    StringTokenizer inReader = new StringTokenizer(textLine,"\t");
    if(inReader.countTokens() != 7)
    throw new IOException("Invalid Input Format");
    else {
    String patientName = inReader.nextToken();
    String nameOfParent = inReader.nextToken();
    String phoneNum = inReader.nextToken();
    int birthYear = Integer.parseInt(inReader.nextToken());
    int birthMonth = Integer.parseInt(inReader.nextToken());
    int birthDay = Integer.parseInt(inReader.nextToken());
    char sex = inReader.nextToken().charAt(0);
    GregorianCalendar dateOfBirth = new GregorianCalendar(birthYear, birthMonth, birthDay);
    Patient newPatient = new Patient(patientName, nameOfParent, phoneNum, dateOfBirth, sex);
    patientDB.addElement(newPatient);
    console.close();
    *note that the constructor actually reads a file and tokenizes each element to an attribute, and each attribute is passed through the constructor of the Patient class to instantiate the object.  it then stores the object into the vector as an element.
    based on this, i would like to sort the vector according to the object's patientName attribute, alphabetically. can anyone out there help me on this?
    i have read most of the threads posted on this forum regarding similar issues, but i don't really understand on how the concept works and how would the Comparable be used to compare the patientName attributes.
    Thanks for your help, guys!

    Are you sure that you will always sort for the patient's name throughout the application? If not, you should consider using Comparators rather than implement Comparable. For the latter, one usually should ensure that the compare() method is consistent with equals(). As for health applications it is likely that there are patients having the same name, reducing compare to the patient's name is hazardous.
    Both, Comparator and Comparable are explained in Sun's Tutorial.

  • Error #1034 Type Coercion fail with registerClassAlias and nested Vectors

    I'm attempting to use flash.net.registerClassAlias and ByteArray.writeObject in order to serialize/deserialize data with static type information.  It works as you'd expect in the general case but I've run into problems with some nested Vectors that I don't understand.  Hopefully someone can point out if I'm just missing something.
    For what I understand, we must register both the scalar types and a one-deep specification of a Vector for that scalar type in order to use nested Vectors.  For example:
                flash.net.registerClassAlias("TestStructureInner", TestStructureInner);
                flash.net.registerClassAlias("VectorTestInner", Vector.<TestStructureInner> as Class);
    This should allow us to read/write objects of type TestStructureInner, Vector.<TestStructureInner>, and Vector.<Vector.<TestStructureInner>> into ByteArrays.  And in general it seems to work.
    Attached though is a simplified test case that fails, however.  The first time we deserialize the data it works.  The subsequent time, however, we encounter the following runtime error #1034.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fcb9 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fbc9 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fdd1 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fce1 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fbf1 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fec1 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fad9 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304fa61 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304f9e9 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
        TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@304f971 to __AS3__.vec.Vector.<__AS3__.vec::Vector.<Test0.as$30::TestStructureInner>>.
    Re-registering the class aliases again via flash.net.registerClassAlias works in this test case but isn't 100% for our actual application (I'm reticent to even mention it but it seems relevant).  Is there a step I'm missing here?  Any light shed would be appreciated.
    // mxmlc -debug Test0.as
    package
        import Base64; // http://code.google.com/p/jpauclair-blog/source/browse/trunk/Experiment/Base64/src/Base64.a s
        import flash.net.registerClassAlias;
        import flash.events.Event;
        import flash.utils.ByteArray;
        import flash.display.Sprite;
        import flash.display.Stage;
        import flash.system.System;
        public class Test0 extends Sprite
            static private const OPERATION_SERIALIZE:uint = 0;
            static private const OPERATION_DESERIALIZE_AND_FAIL:uint = 1;
            static private const OPERATION_DESERIALIZE_AND_SUCCEED:uint = 2;
            static private var staticStage:Stage;
            private var bar:Vector.<TestStructure>;
    * common functions
            static private function registerClassAliases():void
                flash.net.registerClassAlias("TestStructureInner", TestStructureInner);
                flash.net.registerClassAlias("VectorTestInner", Vector.<TestStructureInner> as Class);
                flash.net.registerClassAlias("TestStructure", TestStructure);
            static public function staticDeserialize():Object
                var byteArray:ByteArray = Base64.decode("EBUAG1Rlc3RTdHJ1Y3R1cmUKEwAHZm9vEAEAH1ZlY3RvclRlc3RJbm5lcgoBEAEABAoBEAEABA oBEAEABAoBEAEABAoBEAEABAoBEAEABAoBEAEABAoBEAEABAoBEAEABA==");
                byteArray.position = 0;
                return byteArray.readObject();
            public function Test0():void
                registerClassAliases();
                // Switching operation between the constants demonstrates failure/success in a couple of different ways.
                // SERIALIZE is just used to prepare the base64 string for subsequent tests.
                var operation:int = OPERATION_SERIALIZE_AND_FAIL;
                if (operation == OPERATION_SERIALIZE)
                    trace("Serializing");
                    // outputs base64 string for subsequent tests
                    serialize();
                else if (operation == OPERATION_DESERIALIZE_AND_FAIL)
                    trace("Fail case");
                    // perform successful one deserialization, then one failing one.
                    deserializeOnceThenFail();
                else if (operation == OPERATION_DESERIALIZE_AND_SUCCEED)
                    trace("Success via re-registration");
                    // perform successful one deserialization, then another successful one.
                    deserializeOnceThenSucceed();
    * serialize
            // outputs base64 string we use for subsequent tests.
            private function serialize():void
                var baz:Vector.<TestStructure> = new Vector.<TestStructure>;
                for (var i:int=0; i<10; ++i)
                    baz.push(new TestStructure);
                var byteArray:ByteArray = new ByteArray;
                byteArray.writeObject(baz);
                trace(Base64.encode(byteArray));
    * deserializeOnceThenFail
            // perform successful one deserialization, then one failing one.
            public function deserializeOnceThenFail():void
                // save stage
                staticStage = stage;
                // the first deserialize will proceed without error.
                staticDeserialize();
                trace("Successful deserialize");
                // add an event listener in order to invoke error on subsequent frame
                stage.addEventListener(Event.ENTER_FRAME, doEnterFrameOnceThenFail);
            // remove event listener and invoke again.
            static private function doEnterFrameOnceThenFail(e:Event):void
                staticStage.removeEventListener(Event.ENTER_FRAME, doEnterFrameOnceThenFail);
                staticDeserialize();
                trace("unsuccessful deserialize2");
    * deserializeOnceThenSucceed
    * Here, we re-call flash.net.registerClassAlias on all our class types when running.
            // perform successful one deserialization, then one failing one.
            public function deserializeOnceThenSucceed():void
                // save stage
                staticStage = stage;
                // the first deserialize will proceed without error.
                staticDeserialize();
                trace("Successful deserialize");
                // add an event listener in order to invoke error on subsequent frame
                stage.addEventListener(Event.ENTER_FRAME, doEnterFrameOnceThenSucceed);
            // remove event listener and invoke again.
            static private function doEnterFrameOnceThenSucceed(e:Event):void
                staticStage.removeEventListener(Event.ENTER_FRAME, doEnterFrameOnceThenSucceed);
                registerClassAliases();
                staticDeserialize();
                trace("successful deserialize2");
    internal class TestStructureInner
              public var value:int;
    internal class TestStructure
              public var foo:Vector.<Vector.<TestStructureInner>> = new Vector.<Vector.<TestStructureInner>>;

    The error would imply that ImageAssetEvent does not inherit
    DisplayEvent. Either modify the inheritance chain or listen for a
    basic Event object (flash.events.Event) and cast inside the
    function.

Maybe you are looking for

  • Problem with displaying panel in a JFrame

    This application is supposed to display the actual month in a calendar with the current day in a red background. When running initially I get the frame with nothing in it, but if I resize it everything is displayed perfectly. I've played with the siz

  • P75 laptop won't power up

    Battery appears to be dead . When I plug in a/c power nothing lights up however the case becomes energized . Confirmed with a Klein voltage tester . Any thoughts? This laptop is 14 months old with a total of 30 hours of use.

  • Error trying to update samples

    The preview download instructions recommend updating the SDK. I am following those instructions have received this error when runing the LiveCycle_ES_SDK\samples\SamplesConfig\bin and run runUninstallSamples.bat Error log >> java.lang.NoClassDefFound

  • 10.6.8 Combo Update Download Broken

    I've been trying to download the 10.6.8 Combo Update, but the download seems to be broken. Instead of the stated 1.09 GB, the download completes after 1.00 GB and the dmg won't mount, citing an error through a pop-up dialog. I've tried downloading in

  • Billing output to IDoc & reprocess the IDoc in same sys. to post FI entry

    I have a requirement to send the billing output to IDoc, read the same IDoc to post a FI entry but to another company code. Please suggest how can this be acheived, and is there any other alternative to acheive the above requirement. Thanks in advanc