Nima February 2016

How to define a public vector in Java?

I am trying to pass a vector of vectors from one class to another one. For regular parameters and arrays I used something like this:

public static double[] x= new double[100];

However, this is not working for a vector or a vector of vectors:

public Vector<Vector<Integer>> vec2 = new Vector<Vector<Integer>>();
public Vector<Integer> vec = new Vector<Integer>();

How can we retrieve a vector of vectors in other classes?

Answers


Aetos February 2016

Consider the following code for your actual problem, maybe it could help you understand better :

    //These are the Integers your vector will contain
    Integer i1 = new Integer(1);
    Integer i2 = new Integer(2);
    Integer i3 = new Integer(3);
    Integer i4 = new Integer(4);

    //This is the vector you're going to insert them into (You could create more than one)
    Vector <Integer> v1 = new Vector<>();

    v1.add(i1);
    v1.add(i2);
    v1.add(i3);
    v1.add(i4);

    //This is the vector of vectors you're going to use to contain your previous vector
    Vector <Vector<Integer>> vectorOfVectors= new Vector<>();

    vectorOfVectors.add(v1);

    //To test out your code
    System.out.println(v1.toString());
    System.out.println(vectorOfVectors.toString());

But consider not using the Vector class as suggested in the following post : Why is Java Vector class considered obsolete or deprecated? There are better options such as the Collection Interface's ArrayList.

The Java tutorial offers a complete guide as to how to use the Collections Interface. I suggest you study it closely as it is really useful for any type of collections you could need. Here's the link.

Post Status

Asked in February 2016
Viewed 2,718 times
Voted 7
Answered 1 times

Search




Leave an answer