简体   繁体   中英

array of pair, ArrayList in java

how can I make array of ArrayList or Pair Class which I made myself at the code below.

ex1)

import java.util.*;

class Pair{
  static int first;
  static int second;
}

public class Main{
  public static void main(String[] args){
    Vector<Pair>[] v = new Vector<Pair>[100](); //this gives me an error
  }
}

1.why the code above gives me an error? 2.my goal is to make an array of vector so that each index of vector holds one or more Pair classes. How can I make it?

another example) : array of ArrayList

import java.util.*;

public class Main{
  public static void main(String[] args){
    ArrayList<Integer> arr = ArrayList<Integer>(); //I know this line doesn't give error
    ArrayList<Integer>[] arr = ArrayList<integer>[500]; // this gives me an error
  }
}

3.why does the code above give me an error? 4.my goal is to make an array of ArrayList so that each index of Array has ArrayList/Queue/Vector/Deque whatever. How can I make it?

完整的通用解决方案如何:

ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();

The syntax you have used is not what Java uses. If you want to have an array of ArrayLists then do:

ArrayList[] arr = new ArrayList[100];

for(int i=0; i<arr.length; i++)
{
    arr[i] = new ArrayList<Pair>(); // add ArrayLists to array
}

Here the type argument <Pair> specifies that the ArrayList should contain items of type Pair . But you can specify any type you wish to use. The same goes for ArrayList, you could replace ArrayList with Vector in the example.

It would be best to use an ArrayList instead of an array in the example. Its much easier to maintain without worrying about the changing length and indexes.

Hope this helps.

public static void main(String[] args){
    Vector[] v = new Vector[5];
        for(int i=0;i<5;++i){
            v[i]= new Vector<Pair>();
    }
  }

I don't know java that well, but don't you want to do: ArrayList<ArrayList<Pair>> v = new ArrayList<ArrayList<Pair>>();

Try to break down what containers you need in your question. Your goal is to make a ArrayList (ok, the outer ArrayList satisfies that purpose) that has one or more pair classes in that . "That has" means that "each item in the ArrayList is this type". What would we use to store one or more Pair classes? Another Vector/List of tyoe Pair . So each item in the outer ArrayList is another ArrayList of Pairs.

Note: I moved everything to ArrayList because I read that Vector is somewhat deprecated and they serve similar functions. You may want to check on this.

This example should help with with the next part of your question, but let me know if it doesn't,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM