Vectors in Java, how to return multiple vectors to an object

I am working on a java program and I have several vectors defined and populated (from a file) inside a method. I need to return the contents of all vectors from a method. I heard that you can put them all in one object to get them back. Is this possible, and if so, how? If not, do you have any possible solutions for me? Thanks in advance for your help!

Here's a snippet of code:

Object getInventory()
{       
        Vector<String> itemID=new Vector<String>();
        Vector<String> itemName=new Vector<String>();
        Vector<Integer> pOrdered=new Vector<Integer>();
        Vector<Integer> pInStore=new Vector<Integer>();
        Vector<Integer> pSold=new Vector<Integer>();
        Vector<Double> manufPrice=new Vector<Double>();
        Vector<Double> sellingPrice=new Vector<Double>();  
        Object inventoryItem=new Object(); //object to store vectors in

    try
    {
        Scanner infile= new Scanner(new FileReader("Ch10Ex16Data.txt"));

        int i=0;

        while (infile.hasNext())
        {                
            itemID.addElement(infile.next());                
            itemName.addElement(infile.next()+infile.nextLine());
            pOrdered.addElement(infile.nextInt());
            pInStore.addElement(pOrdered.elementAt(i));
            pSold.addElement(0);
            manufPrice.addElement(infile.nextDouble());
            sellingPrice.addElement(infile.nextDouble());
            i++;

        }
        infile.close();

        System.out.println(itemID);
        System.out.println(itemName);
        System.out.println(pOrdered);
        System.out.println(pInStore);  
        System.out.println(pSold);
        System.out.println(manufPrice);
        System.out.println(sellingPrice);

    }
    catch (Exception f)
    {
       System.out.print(f);
    }

     return inventoryItem;
}

      

0


source to share


8 answers


Actually, I will completely abandon this approach. You seem to want the Product class:

public class Product {

    private String itemName;
    private int itemID;
    // etc etc

    public Product(String itemName, int itemID) {
       this.itemName = itemName;
       this.itemID = itemID;
       // etc etc
     }

    public String getItemName() {
       return itemName;
    }

     public int getItemID() {
      return itemID;
    } 

    // etc etc
}

      

Then something like this:



public class Invertory {

 private List<Product> products = new ArrayList<Product>
 // etc etc

public Inventory(String fileName) throws IOException {
      // Load file,
       // Read each product, 
       products.add(new Product(...product arguments); //add to array
  }

  public Product[] getProducts() {
      return products.toArray(new Product[]{});
  }

      

}

+9


source


First of all, use ArrayList instead of Vector. Then use a map as a return object, each value of which is one of your lists.

Second, a much better approach is to create an object that actually stores each of your fields and returns a java.util.List from those objects.



public class Item
{
    String id;
    String name
    Integer pOrdered;        
    Integer inStore;
           :
           :

      

+3


source


You should really revisit your design here. You have multiple vectors, each with properties of the same type of item - an item in your inventory. You should probably turn this into one class, possibly InventoryItem

with members for name, price, etc. Then when you read into each element, you create InventoryItem

with the given properties and return one Vector<InventoryItem>

.

If you are really tied to keeping track of all those individual Vector

s, you can simply return Vector[]

with all your vectors:

return new Vector[] { itemID, itemName, pOrdered, pInStore, pSold, manufPrice, sellingPrice };

      

Also, as Robin says , you should use a container ArrayList

instead of Vector

. The only thing that will change is that you need to change all calls to someVector.AddElement

to someList.add

.

+1


source


You are making several mistakes.

First, don't use Vector. As usual. If orders are important to you, you need a list in the API (and perhaps an ArrayList or LinkedList as an implementation).

Second, you are trying to have a large number of arrays that have values ​​that fail. It's almost impossible to use. Just create a class representing one record and return a list of them.

Third: don't catch this exception. You don't know what to do about it and you will just confuse yourself. Only catch the exception if you have a really good idea of ​​what to do in the event of an error (printing out an error message without a stack will almost never be correct).

Your method signature is the most important part. If you get it right, implementation doesn't matter much in the same way. Please post something similar to this:

List<Item> getInventory(File input) throws IOException {
}

      

+1


source


It looks like it should be labeled Homework.

Ok, firstly, should you use all of these Vectors or is this your own solution? While some may indicate that it is better to use ArrayLists, I would do away with them and create my own Item class.

So, instead of having the properties of a conceptual item spread across multiple vectors (which is how you currently do it), you have 1 instance for each item, with fields for all data related to that item. Now you only need one data structure (Vector or ArrayList) for all the objects in the object, and you can return that structure from getInventory ().

0


source


The easiest way to declare an object is something like

List<Vector<? extends Object>> inventoryItem = new ArrayList<Vector<? extends Object>>

      

but this has a couple of problems, namely that Java generics are not validated, so you have to check and discard the contents of every vector you return. A better solution would be to define a container object that has each of the vectors as fields and adds to them.

However, it looks like this is really missing. Instead, you must define an InventoryItem that has each of your seven fields. Every time you read an object from a file, create a new InventoryItem instance and fill in its fields. Then you add this to one vector.

Also, it is generally recommended that you do not use the Vector class. You should use ArrayList instead. A vector should really only be used if you need its synchronization properties, and even then you should consider carrying some other list into Collections.synchronizedList ().

Finally, the places where you only want to catch the Exception can be counted on one side. You should really catch the IOException and even might want to consider a simple recovery. Also, you must call printStackTrace () for the exception, not System.out.println ().

0


source


I find it a good rule of thumb to never pass collections around your objects. They are obviously useful inside your object, but outside of you they lose control and they are not obvious.

Let's consider the principle of reading code instead of documenting it. If you are taking a collection, how does this tell the caller what to pass? Even if you are using generics, there is no way to assert what happens to the collection - someone can add to and remove from it in another thread after it has been passed to you.

There is no reason not to create a business class that contains your collections along with business logic in order to manipulate them (yes, there is always business logic - this is the copy and paste code that you find where you access the collection).

I had to frustrate that the JDK always seems to take arrays of built-in types rather than collections, but it becomes clearer when you accept the idea that passing collections (like passing any base type) is not a good idea.

0


source


While I generally agree with the advice to use List / ArrayList instead of Vector, it's important to know why. Indeed, I must vehemently disagree with Dustin, who says not to use Vector "ever".

A Vector is essentially a synchronized ArrayList. If you really need sync, by all means, ignore Dustin's warning and use Vector.

There is another example where Vector is justified. And that's when you need to maintain compatibility with the pre-Java2 codebase.

-1


source







All Articles