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).

hyde
  • 50,653
  • 19
  • 110
  • 158
  • 3
    `vector v[20]` is **not** a vector of vectors. – juanchopanza Oct 20 '13 at 19:55
  • Related: http://stackoverflow.com/questions/7810074/array-of-generic-list and http://stackoverflow.com/questions/217065/cannot-create-an-array-of-linkedlists-in-java – hyde Oct 20 '13 at 20:29

3 Answers3

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);
Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
  • 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! –  Oct 20 '13 at 20:06
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.

Joop Eggen
  • 96,344
  • 7
  • 73
  • 121
  • Why `Integer.class`, specifically? I mean, is there a technical reason, is it common convention, or just your personal preference? – hyde Oct 20 '13 at 20:31
  • You mean int being a primitive type, Integer the object wrapper. `List` 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. – Joop Eggen Oct 20 '13 at 20:43
  • **Sorry**, should have been `List.class`. – Joop Eggen Oct 20 '13 at 21:19
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);//....
    }

}