An array of ArrayLists...

I've been trying to create an array of ArrayLists, and have been unsuccessful.
class program {
     static ArrayList<String>[] var;
     void method () {
          var = new ArrayList<String>()[5];
}The error message I get is "array required, but java.util.ArrayList<java.lang.String> found"
Am I doing something wrong, or is there a better way to accomplish what I'm trying to?

import java.util.ArrayList;
import java.util.List;
class W
     public static void main(String[] args)
        List<String> list1 = new ArrayList<String>();
        list1.add("a");
        list1.add("b");
        List<String> list2 = new ArrayList<String>();
        list2.add("c");
        list2.add("d");
        List[] anArray = {list1, list2};
        System.out.println(anArray[0].get(1)); // "b", from 1st array element, 2nd list1 element
}

Similar Messages

  • How to create an array of ArrayLists?

    Hello,
    I'm trying to compile the following code:
    ArrayList<Object> arr[];
    arr = new ArrayList<Object>()[size];in order to create an array of ArrayLists. I'm being met with the following compilation error:
    The type of this expression must be an array type but it resolved to ArrayList<Object>
    Can anyone show me how to correctly do this?
    Thanks

    {color:#3D2B1F}This line:
    List<Object>[] arr = new ArrayList<Object>[5];generates the compiler error: "generic array creation" (generics and arrays don't play well together)
    Since you are just parameterizing with Object, you can use non-generic collections:
    List[] arr = new ArrayList[5];Me? I don't like mixing arrays and collections. I would have a list of lists:
    List<List<X>> matrix = new ArrayList<List<X>>();{color}

  • Finding top five number in an array of arraylists.

    I have to write a method with a heading
    public static int [] findTopFiveMostSteps ( ArrayList [] temp )i will input an array of arraylists, and I have to write this method
    that will return a integer array containing the top five number in that
    array of arraylists.
    I have no idea how to go on about this
    please help

    How would you do it "manually"? That is, if you just
    had pencil and paper and several lists of numbers,
    what would be the steps? Keep them very simple and
    precise.Socrates would be so proud.
    I was just reminiscing about how I once tried to teach Java to the web designer
    at my last job. I gave him the task of writing:
    static int max(int[] values) He just didn't grok it:
    Me: How would you figure it out by hand?
    WD: I'd look at the numbers and pick the biggest.
    Me: Break that down into steps.
    WD: I'd -- look -- at -- the -- numbers -- and -- pick -- the -- biggest.
    In the end, we tacitly agreed to stop the teaching and hope the manager didn't notice.

  • Converting Array to ArrayList not working

    Dear Members :
    Following line fails to convert my array to arraylist:
    List myArrayList = Arrays.asList(myArray);
    bcoz when I do
    System.out.println("ArrayList: "+myArrayList);
    it returns [[I@3e25a5]. The array is just a standard array: int[] myArray.
    I even tried with: List myArrayList = new ArrayList(Arrays.asList(myArray)); but same.
    Could you please suggest a solution to this ?
    Thanks in advance.
    Atanu

    YoungWinston wrote:
    Darryl Burke wrote:
    YoungWinston wrote:
    I agree, although experienced programmers would probably realize it already.Varargs existed in Java before I ever started learning it. Today for the first time, I'm beginning to understand why some programming veterans hate the feature.I think it has more to do with the <T> .... (T... array) {in the method signature. Generic types can only be references.Agreed. But it's the varargs that obscure the fact that an <tt>int[]</tt> may be treated as a single <tt>T</tt> parameter while an <tt>Object[]</tt> is treated as a <tt>T...</tt>. Which probably has something to do with the attitude of some veteran programmers to autoboxing as well.
    db

  • Trouble with an Array of ArrayList

    Hi I've created an array of ArrayLists as follows:
    public static ArrayList<BasicSimulationApp>[] clientHashTable = (ArrayList <BasicSimulationApp>[]) new ArrayList<?>[numBins];
    Unfortunately, I keep getting a warning:
    Type safety: The cast from ArrayList<?>[] to ArrayList<BasicSimulationApp>[] is actually checking against the erased type ArrayList<E>[]     
    I've tried a number of different solutions including trying to make clientHashTable of type clientHashTable<?>[] but then I get warnings when I try to use this array. If I try to initialize clientHashTable as new ArrayList<BasicSimulationApp>[numBins] I get an error saying that cannot create a generic array of type <BasicSimulationApp>.
    Can anyone suggest what I can do to get rid of the warning? Apart from turning the warning off of course ;)

    When you are using Generics with arrays you'll always end up with warnings.
    One thing you can try out is to use the latest addition of @SuppressWarnings Annotation Tag.

  • Storing 2d array in ArrayList?

    Hi I'm storing a 2d int array (int[][]) in an ArrayList. But I cant convert it back to a 2d array again.
    Tried:
    indices.add(option.getIndexList());
    indices.add(option[j].getIndexList());
    int[][] Arr = (int[][])indices.toArray(new int[indices.size()][2]);

    If you put a 2-d array into an ArrayList, then toArray would make a 3-d array--a 1-d array of 2-d arrays.
    However, I don't think you can use toArray to get a primitive array. If you look at the API, it requires an object. I think you'll have to do this to get each array:
    int [][] arr = (int[][])indices.get(0);If you want the 3-d array, you can do it manually.

  • Regarding Array and ArrayList

    Hi all,
    if any body knows the difference between Array and Array List Conceptually tell me the differences..
    Thanks ,
    Naveen

    An array is a less dynamic structure than an ArrayList. An array gets a fixed size once it's created. It's memory is allocated upon creation, generally these are sequential memory locations.
    An ArrayList provides the same features as an Array: you can acces the contents by index. It add the features of a List to it: getting the head, traversing contents, inserting, appending... It also can grow in size dynamically. This is done by giving each element in an ArrayList a reference to the next element. This allows the elements to be stored throughout the available memory.

  • Arrays vs ArrayList

    When we have arrays in java, why did they provide arraylist? What is the basic advantage of ArrayList over Array?
    Thanks in advance

    When we have arrays in java, why did they provide
    arraylist? What is the basic advantage of ArrayList
    over Array?
    Thanks in advanceLook at the API that would answer your question. All the functionality available for Arraylist is it available for arrays as well.
    It is very similar to asking why have String class when you can have an array of chars.
    Sun is just trying to make your life easy

  • Arrays vs arraylists

    How do you guys determine whether to use arrays or the arrayList? I've seen situations where arrays are used that I thought arrayLists were more fitting. Is there some kind of performance penalty when using arrayLists over arrays?
    Thanks in advance!

    Array are more efficient rispect to ArrayList, but the dimension of an array can be decided only once:
    Array a = new Array[20] \\ this array will never contain 21 elements
    ArrayList are dinamically reallocated each time you add a new element
    Another thingh is thata when you istance a Array variable you will immediatly reserve a portion of memory for all the elements of the array
    When you istance a ArrayList variable you only create the variable but there will be memory allocation only for the inserted elements
    So:
    If you know in advance the max number of elements of the array probably you need an Array
    If you know the max number of element, this number if very hight, and you know that the max part of the program there will be very less element you probably will choose ArrayList to use less memory
    If you totally dont know how many elemnts you have to manipulate you have to chose an ArrayList.
    Hope it's enought (and not Wrong)
    Riccardo Coletta

  • Help needed!2D array or ArrayList?

    Hi,
    I need help!
    I have a dataset 'cellSig.txt' with data like '34.5,42,200,52,654,58,92.0,45.6,0.'
    I need to write a program which would divide the dataset of 3000 seq (like above) into two datasets 'train' of size 2000 and 'test' of size 1000 selecting the seq randomly . The two datasets should not have duplicates and be similar to each other.
    Using Arraylists I can randomly select the seqs and add them into a new file ..however how do I remove the selected seqs from the main file 'cellSig.txt' so that I can use the remaining 1000 seqs for the test file?
    Any help would b greatly appreciated.
    Regards
    Nis

    Crossposted:
    http://forum.java.sun.com/thread.jspa?threadID=629166

  • Quickie - How to create a ArrayList Array?

    Hi,
    I hope this has a quick answer. What I'm trying to do is create an Array of ArrayList objects to replace a ragged array I had for strings. Basically the length of each 'row' of the array can be variable and I want to take advantage of ArrayLists features. So I created ArrayList
    as below:
    ArrayList[] headerInfo = new ArrayList[3];
    headerInfo[0] = new ArrayList<String>();  
    headerInfo[0].add("aString");If I iterate through each arrayList using a for each loop, will the order be preserved? Or is there a better way to achieve a 'variable length' ragged array?
    Thanks.

    Also, if you end up having to keep a large number of empty spaces in your lists/arrays (so that the "x" and "y" line up with the object you are trying to represent), you can try a Map to reduce the overall memory needed (because you won't need to keep a space for "x,y" pairs that don't have a corresponding value). Your key can be a String generated as:
    String key = x + "," + y;Then your map could be:
    Map<String, String> myStrings = new HashMap<String, String>();The getString method would be:
    return myStrings.get(x+","+y);or the key could be a simple class:
    [For a HashMap, you need hashCode--maybe add the hashCode provided by Integer class for x to the hashCode provided by Integer class for y--I don't know a lot about implementing hashCodes, but that sounds possibly reasonable.]
    class Pair {
       private final int x;
       private final int y;
       Pair(int x, int y) {
          // set values
       // define "equals" (x == other.x, y == other.y)
       // define "hashCode"
       // define "toString" for debugging purposes
    Map<Pair, String> myStrings = new HashMap<Pair, String>();The getString method would be:
    return myStrings.get(new Pair(x, y));For mathematics, if the 2-d array was a numerical matrix, this HashMap would implement what is called a "sparse matrix".
    The map doesn't change your other classes. The other classes would still call:
    String myString = someClass.getString(2, 4);

  • Help :add multiple rows from Resultset to ArrayList ?

    My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
    ex:
    item_num
    p001
    p002
    p003
    when I print, it only gets the item in the first row.
    ArrayList myArrayList = new ArrayList();
    resultset = preparedstatement.executeQuery();
    if (resultset.next())
    myArrayList.add(new String(resultset.getString("item_num")));
    Print:
    for (int j = 0 ; j < myArrayList.size() ; j++ )
    System.out.println((String)myArrayList.get(j)); --this prints only the first item.
    can someone assist ?

    changing if to while fixed it.

  • A bunch of ArrayLists

    Overview
    My program needs to store 11 different types of data (numbered 1 through 12, skipping 5, although I may find a way to fill this gap soon). Each type of data needs to have a bunch of entries of undeterminate size (ArrayList), but I know there will always be 11 different types of data. I figured instead of having 11 different ArrayList variables and 11 getters, 11 setters, and 11 removers, I could just store them all in an array of some sort, and then only have 1 getter/setter/remover/etc which takes an argument of what data type it is.
    Problem
    Problem is, I'm not exactly sure what to use to group these ArrayLists together. I tried an array, but it complains about the generic typing:
    ArrayList<Resource> resList[] = new ArrayList<Resource>[13]();
    or any combination/order of [13] and () and it always complains "Cannot create a generic array of ArrayList<Resource> or "Cannot convert from ArrayList<Resource> to ArrayList<Resource>[]"
    Solution
    Using basic google skills, I discovered I could use:
    ArrayList resList[] = new ArrayList[12];
    essentially just dropping the type...
    and then loop through the 13 new ArrayList<Resource>();
    Resulting Problem
    Then when I go to add one of the datatypes to its respective data type ArrayList
    resList[Resource.PATH].add(new Path());
    it warns me: "...Type Safety... raw type ArrayList... should be Parameterized"
    it also says the same thing, somewhat surprisingly, when I generalize the path data type back down to Resource:
    resList[Resource.PATH].add((Resource)new Path());
    since I did declare each arraylist of type <Resource>. Yet it makes the same complaint.
    Conclusion
    There's basically 4 possible outcomes to this that I can think up.
    1) (Mostly desirable) There is a solution to my Type Safety warning.
    2) (Undesirable) use @SuppressWarnings
    3) An alternative to bunching them in arrays (I had a glance at Arrays.asList, but wasn't so sure about it)
    4) (Undesirable) just leave them as 11 different ArrayList variables and make them public.
    Thanks in advance,
    -IsmAvatar

    @musicalscale, thanks, I think. Is this just creating
    an ArrayList of ArrayLists? Because I don't think
    that's appropriate here because the 11 data types are
    unchanging (until I fill in the gap at 5, in which
    case it's simply a matter of slight recoding which
    I'm more than happy to do).Yes, it's an ArrayList of ArrayLists. It will get rid of the generics warnings. If you don't plan on changing the size of the outer ArrayList, then you don't have to change it. Only your one class that keeps the private ArrayList of ArrayLists will have direct access to the outer list (unless you code it otherwise). So, you don't have to worry that someone else will mess up the list.
    Or, after you create the initial list of lists, store the private reference as an unmodifiable List:
    private final List< List < Resource > > resList;// In your constructor (or another method):
    // create tempResList with generics as described,
    // then set the instance variable as
    resList = Collections.unmodifiableList(tempResList);Then even your local class can't add or remove things from the outer list (they can still modify the inner lists).
    As for HashMap, I guess it doesn't matter that the
    order may change, since we have the key paired with
    it. But is HashMap also dynamically resizable? Maybe
    I'm just blind to the internal workings.Yes, a HashMap is dynamically resizable. Since you have a key, yes, the order doesn't matter (there is also a TreeMap that keeps the keys sorted, but you don't really need that for your stated purposes). You can make an unmodifiable Map similar to how you make an unmodifiable List.

  • Is there a way you can add elements dynamically to an existing array??

    hey guys... i need to add elements to an array dynamically... how do i do that?
    for example... in one of my functions i do..
         for each(var item:Object in fileList){
              fileListArr.push(item);
    and in a later function i need to add one more element to my fileListArr...
    so i tried doing
    fileListArr[indexNum].push({
         key:videoKey
    so i need to have an array which resembles something like this...
    Before adding elements...
    fileListArr:
         [0]:  name:test1
                Size:12K
                caption:testing caption
                number:1
         [1]:  name:test2
                Size:12K
                caption:testing caption
                number:2
    after adding key to array
    fileListArr:
         [0]:  name:test1
                Size:12K
                caption:testing caption
                number:1
                key:xyxyyy11y1yy1y1y2y2u33n
         [1]:  name:test2
                Size:12K
                caption:testing caption
                number:2
                key:iiduudjmenri112jj2n4n3m2j1j21
    any ideas?

    hmm interesting... so i made the changes... i changed the array to arraylist and the code i have is as follows... but i still get an error... the error says ... "ReferenceError: Error #1056: Cannot create property key on flash.net.FileReference."
    public var videoReference:VideoHandler;
    public var fileRef:FileReferenceList = new FileReferenceList();
    [Bindable] public var fileListArr:ArrayList = new ArrayList();
    [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
    public function selectionHandler(event:Event):void{
         fileRef.removeEventListener(Event.SELECT, selectionHandler);
         var numSelected:int = event.target.fileList.length;
         var fileList:Array = event.target.fileList;
         for each(var item:Object in fileList){
              fileListArr.addItem(item);
              fileNames.addItem({
                   num: fileNames.length + 1,
                   name: item.name,
                   size: formatFileSize(item.size),
                   status: ""
         var newListLength:Number = fileListArr.length;
         if(fileCounter > 0){
              loopList(fileCounter);
         else
              loopList(0);
    public function loopList(value:int):void{
         //trace("looplist -->");
         if(value < fileListArr.length){
              _numCurrentUpload = value;
              file = new FileReference();
              file = FileReference(fileListArr.getItemAt(value));
              file.addEventListener(Event.COMPLETE, loadVideo);
              file.addEventListener(ProgressEvent.PROGRESS, fileProgress);
              file.load();
    public function setUploadKey(event:ResultEvent):void{
         if(event.result.ThereWasAnError){
              Alert.show(event.result.ErrorMessages[0]);
         }else{
              videoKey = event.result.UploadKey;
              if(fileCounter >= fileListArr.length){
                   trace("in if");
                   fileCounter = 0;
                   uploadLoopList(fileCounter);
              }else{
                   trace("in else");
                   //fileListArr[fileCounter - 1]['videoKey'] = videoKey;
    -----> get an error here --->fileListArr.getItemAt(fileCounter - 1).key = videoKey;
                   //fileListArr[fileCounter - 1] = [{key: videoKey}];
                   loopList(fileCounter);

  • How can I rank a group of numbers in a array or list

    Now I have a group of numbers :13, 4, 5, 10.
    I need a java algorithm to rank those numbers, the result will be like 4,1,2,3 after ranking.
    suppose there are same numbers in the source, for example: 13, 4, 4, 5, 6
    the result will be like 4, 1, 1, 2, 3 after ranking.
    Thank you for any help!

    Another alternative is to make a class which has two attributes
    1. number value
    2. rank
    make this class implement comparable so you sort it anyway you like. Below is a very close example of what you are looking for, just need to replace frequency with rank
    class ComparbleExample{
        private final String[] possibleNumbers = {"one", "two", "three"};
        private String[] inputNumbers = {"one", "two", "three", "one", "one", "four", "three"};
        private Number[] numbers;
        public ComparbleExample(){
            numbers = new Number[possibleNumbers.length];
            populateNumberArrayList();
            System.out.println("\n\nPrinting Unsorted Array");
            print();
            ArrayList<Integer> d;
            Arrays.sort(numbers);
            System.out.println("\n\nPrinting Sorted Array");
            print();
        public void populateNumberArrayList(){
            int frequency;
            for(int i = 0;i<numbers.length;i++){
                frequency = getFrequency(possibleNumbers);
    numbers[i] = new Number(possibleNumbers[i],frequency);
    public int getFrequency(String number){
    int frequency = 0;
    for(int i=0;i<inputNumbers.length;i++){
    if(number.equals(inputNumbers[i])){
    frequency++;
    return frequency;
    public void print(){
    for(int i = 0;i<numbers.length;i++){
    System.out.println(numbers[i]);
    public static void main(String[] args){
    new ComparbleExample();
    class Number implements Comparable{
    private int frequency;
    private String number;
    public Number(String number){
    this(number, -1);
    public Number(String number, int frequency){
    this.number = number;
    this.frequency = frequency;
    public String getNumber() {
    return number;
    public int getFrequency() {
    return frequency;
    public void setFrequency(int frequency) {
    this.frequency = frequency;
    public void setNumber(String number) {
    this.number = number;
    public int compareTo(Object o) {
    Number n = (Number)o;
    if(frequency < n.getFrequency()){
    return 1;
    }else if(frequency > n.getFrequency()){
    return -1;
    }else{
    return 0;
    @Override
    public String toString() {
    return this.number +", "+ this.frequency;

Maybe you are looking for

  • Reinstalling Elements 11 is not fixing my problem with Adobe Premiere Elements 11

    Getting Error Message: Runtime error trying to open Organizer or New Project.  Have not been able to open a project, without having an administrator account, so eveytime it's just trying to make a new project.  Only 1 user needs this application, but

  • FRM-92100 Your connection to the server was interrupted in OAS (10.1.2.3.0)

    Hi, A user in WAN getting below error while accesing forms applicaiton But the same is working in LAN without any such type of Error. FRM-92100 Your connection to the server was interrupted This may be the result of a network error,or a failure on th

  • User id type for connecting Universe with SAP BI

    Hi All, I am working on SAP BO XI 3.1 SP3 and I am successfully able to connect Bex query to the Universe. While creating a connection within Universe, we have to provide SAP BI logon parameters like Application IP, user id, password, etc while conne

  • Keypad in as3

    hey guys, Looking to do a keypad in as3. So i have 10 numeric buttons, labelled num1-num10. I have a dynamic textbox that I'll show my presses. How do you record button clicks or keyboard presses of a certain number and display in the text box?

  • I need material for BAPI , BADI  & also programming snapshots.

    hi thisi poojala, I need material for BAPI, BADI . I need some pgms on BAPI, BADI with d snapshots. Can u send material to this mail Id  : [email protected] Thnaks&Regards, Poojala.