2

In c++ we can have this kind of vectors:

vector < int > v[20];

I have to create the equivalent in java of a program in c++. I can declare

static ArrayList < ArrayList<Integer > > v;

but it's not quite what I want. I want it to be more intuitive. I am trying to find a way to easily add elements in my structure. For example if I have a graph and I am reading a road from a to b, in C++ a simply use v[a].push_back(b).

2

3 Answers 3

1

First of all vector<int> v[20] is not vectors of vector.

Secondly ArrayList could be the equivalent of std::vectors in Java.

The general equivalent of vector.push_back could be like this ie, using generic list:-

List<Integer> x = new ArrayList<Integer>();
x.add(1);
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I have in C++ : for(int i = 1; i<=m ; i++) { in>>a>>b; v[a].push_back(b); } I can not use add as you said!
1
    List<Integer>[] v = (List<Integer>[]) Array.newInstance(Integer.class, 20);
    {
        for (int i = 0; i < v.length; ++i) {
            v[i] = new ArrayList<>();
        }
    }

Sadly, Java is not so concise or well designed here. Array.newInstance serves for all dimesions: int[][][] would be Array.newInstance(int.class, 10, 10, 10). Hence it returns an Object as least denominator, and needs to be cast.

The initial array contains only nulls, and needs an initialisation.

Correction:

Should of course be List.class not Integer.class.

3 Comments

Why Integer.class, specifically? I mean, is there a technical reason, is it common convention, or just your personal preference?
You mean int being a primitive type, Integer the object wrapper. List<int> is not possible, a List contains objects only. There are non-standard libraries for an int list. However with boxing you may put an int into the list etcetera.
Sorry, should have been List.class.
1
import java.util.Vector;


public class Main {


    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector[100];
        for(int i = 0; i < anArray.length; i++)
           anArray[i] = new Vector<Integer>();
        anArray[2].add(2);//....
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.