开发者

array of pair, ArrayList in java

开发者 https://www.devze.com 2023-03-25 09:42 出处:网络
how can I make array of ArrayList or Pair Class which I made myself at the code below. ex1) import java.util.*;

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?


How about a full generic solution:

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,

0

精彩评论

暂无评论...
验证码 换一张
取 消