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.

Similar Messages

  • User to enter values and stored as array

    Hi,
    I have some problem with my labs that I would like to clear by doubt.
    I need a user to keyed in a list of age so to calculate the average age. The values entered is stored in into an Array (not arrayList) I have been using ArrayList rather than array. =(
    So I have used a bufferedReader to capture the input the user keyed in. unlike arraylist, I could not create an array without knowing the size of it.
    Also,
    My following code has some proble, when I run the program and enter 99 as the first value input. The system would terminate. However, when I enter other values than 99, the system would not terminate. Do point out my brainless mistake. Thanks alot.
      public static void main(String[] args) {
             // TODO, add your application code
            int num =0;
             int j = 0;
      boolean stop = false;
              int[] arr = new int[200];
               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                  while(stop == false){
               try {
             num =  Integer.parseInt(br.readLine());
          } catch (IOException ioe) {}
          if(num == 99){
          stop = true;
        arr[j] = num;
        j++;
        }

    seah_ly wrote:
    I need a user to keyed in a list of age so to calculate the average age. The values entered is stored in into an Array (not arrayList) I have been using ArrayList rather than array. =(Yes you are correct in using an ArrayList, however if arrays are required you could mimic the actions of a growing ArrayList by using an array and initializing a new array with double the size of the old array and copying the old elements to the new array. Note this is exactly what an ArrayList does.
    My following code has some proble, when I run the program and enter 99 as the first value input. The system would terminate. However, when I enter other values than 99, the system would not terminate. Do point out my brainless mistake. Thanks alot.
    if(num == 99){
      stop = true;
    }What do you think this does to the while loop?
    Mel

  • 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}

  • Storing an array of checkbox booleans into preferences and retrieving them

    Just wondering how to go about storing an array of JCheckBoxes into a preference and retrieving it. There's 32 checkboxes so if they select, say, 6 of these randomly it should store it in a preference file and retrieve it when the application is loaded so that the same 6 checkboxes remain selected. I'm currently getting a stack overflow error, though.
    import java.util.prefs.*;
    public class Prefs {
         Preferences p;
         GUI g = new GUI();
         public Prefs() {
              p = Preferences.userNodeForPackage(getClass());
              g = new GUI();
         public void storePrefs() {
              for (int i = 0; i < g.symptoms.length; i++) {
                   p.putBoolean("symptoms", g.symptoms.isSelected());
         public void retrievePrefs() {
              for (int t = 0; t < g.symptoms.length; t++) {
                   p.getBoolean("symptoms", g.symptoms[t].isSelected());
    symptoms is the array of checkboxes in the GUI class. Not sure where I am going wrong here. I can do it with strings from textfields etc but this is proving to be an annoyance. :(
    Thanks in advance                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Actually, I have a better example, see below
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.util.prefs.*;
    public class PreferencesTest {
        private Preferences prefs;
        public static final String PREF_OPTION = "SELECTED_MENU_ITEM";
        public void createGui() {
            prefs = Preferences.userNodeForPackage(this.getClass());
            JMenuItem exitAndCloseMenuItem = new JMenuItem("Exit");
            exitAndCloseMenuItem.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
            JMenu fileMenu = new JMenu("File");
            fileMenu.add(exitAndCloseMenuItem);
            JCheckBoxMenuItem[] preferenceItems = {
                new JCheckBoxMenuItem("pref 1"),
                new JCheckBoxMenuItem("pref 2"),
                new JCheckBoxMenuItem("pref 3"),
                new JCheckBoxMenuItem("pref 4")};
            int selectedMenuItem = prefs.getInt(PREF_OPTION, 0);
            preferenceItems[selectedMenuItem].setSelected(true);
            ButtonGroup preferencesGroup = new ButtonGroup();
            JMenu preferenceMenu = new JMenu("Preferences");
            for(int i = 0;i<preferenceItems.length;i++){
                preferenceItems.setActionCommand(Integer.toString(i));
    preferenceItems[i].addActionListener(new menuItemActionListener());
    preferencesGroup.add(preferenceItems[i]);
    preferenceMenu.add(preferenceItems[i]);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    menuBar.add(preferenceMenu);
    JFrame f = new JFrame("Prefernce Test");
    f.setJMenuBar(menuBar);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    public static void main(String[] args){
    new PreferencesTest().createGui();
    class menuItemActionListener implements ActionListener{
    public void actionPerformed(ActionEvent e) {
    JCheckBoxMenuItem jcbm = (JCheckBoxMenuItem)e.getSource();
    prefs.put(PREF_OPTION, jcbm.getActionCommand());

  • Storing an array permanently

    Hi,
    Is there a way of storing an array permanently, so that it stays saved somewhere in a file or something? I need to create an application that stores this array and reads the values from it, without having to re-create the array everytime I run the application.
    Thanks for any help.

    Serialization is flakey (can have many problems when JDK or class is updated), wasteful of space, and IMO should be the implementation of last resort.
    Here's a code snippet of what I would do:
    public void saveArray(Object[] array, File f) throws IOException {
      PrintWriter writer = new PrintWriter(new FileWriter(file));
      for (int i = 0; i < array.length; i++)
         writer.println(array.toString);
    writer.close();

  • Storing an array into the database using jdbc

    Hi,
    i�ve got a problem storing an array into a database. I want to store objects consisting of several attributes. One of these attributes is an array containing several int values. I don�t know exactly what is the best way to store these objects into a database. I have created two tables connected by a one to many relationship of which one stores the array values and the other table stores the object containing the array. Is that ok or should I use another way. It�s the first time I�m trying to store objects containing arrays into a database so I�m very uncertain in which way this should be done.
    Thanks in advance for any tips

    1. You should use blob or longvarbianry type colum to stor that array.
    2. All object in that array should be Serializable.
    3. Constuct a PreparedStatement object
    4. Convert array to byte[] object
    ByteArrayOutputStream baos=null;
    ObjectOutputStream objectOutputStream=null;
    baos = new ByteArrayOutputStream(bufferSize);
    objectOutputStream = new ObjectOutputStream(baos);
    objectOutputStream.writeObject(array);
    objectOutputStream.flush();
    baos.flush();
    byte[] value=baos.toByteArray();
    5. Now you can use PreparedStatement.setBytes function to insert byte[] value.

  • 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

  • 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
    }

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

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

  • Best Practice: Storing an array in MySQL

    Hi,
    I'm working on an app that uses Flex 2, Coldfusion and MySQL.
    I'd like to store an array (or in this case an ArrayCollection)
    into my db. I'm not totally sure if I can do this. I read something
    about PHP having an implode command but I'm wondering what the best
    practice would be for trying to get an array into MySQL via
    ColdFusion.
    I'd be grateful for any advice.
    Novian

    Thanks, mike_the_maven.
    I'm not familiar with that tag but I'll definitely look into.
    I'm also wondering about potentially storing my ArrayCollection as
    a BLOB in MySQL. Any thoughts about this approach?
    Thanks.
    Novian

  • Storing an array of integers in a session

    using the following code:
    int stateCount = 50;
    int[] stateId = new int[stateCount];
    for(int i = 0; i<stateCount;i++){
    stateId[i] = i + 1;
    //so far this all works
    //my problem     
    session.setAttribute("stateId", stateId);
    int[] session_statesId = (int[]) session.getAttribute("statesId");
    System.out.print(session_statesId.length);
    //using this code I recieve an error. I have been able to so this storing a String array in a session but I can't figure out why the int is not working any suggestions?

    that's an easy one: you do not use the same id for storing and retrieving. ever thought of using a defined constant?
    private final static String STATES_KEY = "statesId";
    robert

  • Retrieve LV stored 2D-Array via MySQL C-API

     Hello everybody!
    I am not quite sure, if this is the right place for my question, but I'll just give it try.
    I have a LabVIEW Vi which performs Data Acquistion-Tasks. The Data is stored in a MySQL-Database using the Labview Database Connectivity Toolset. One part of the stored data is a 2D-Double-Array. For storage in MySQL It is automatically converted to Binary Data and the stored in a MySQL Blob-Field.
    Unfortunately, the software to process the data is written in C++. It was fairly easy to establish the communication between my c++ application and MySQL via the MySQL C-API. But now i'm struggling to retrieve the Binary-Data from the Database and reconvert it into a C++ Double Array, as am not very experienced with C++.
    Has anyone done something similar before?

    Hello
    I am happy to hear that your LabVIEW application and data storage with the LabVIEW Database Connectivity Toolkit works.
    Unfortunately is this the wrong platform to ask about C++. There are many other open platforms discussing C questions. I’d propose you to ask your question there.
    Best Regards
     Daniela Biberstein
    NI Switzerland

  • Vector (good for storing) and arrays(good for numerical sums, multiplying)

    Hi guys, I am trying to use vectors because I need a variable lenght and store 2D arrays in one coordenate of a vector. That is why I am using vector instead arrays. I can turn the type of variable using "Integer" (instead of "int" as arrays), "Double" (instead of "double") and so on. The problem is that it doesn't allow me to operate, it is very good for storing, but I need to be able to operate, multiplying, sum, etc the elements there are in the coordenates. And I think it is not possible.
    What u think about it? I can only store stuff ion a vector, I cannot operate. Besides I cant turn a data from "Double" to "double", I can either use arrays OR vectors, but not both of them at the same time.
    You think i am wrong?, because I mean in that case, Java is not very useful to do this numerical problem.
    Thanks.
    This is only a class of the program I am doing.
    import java.util.*;
    class SolveDomain {
         int newton_iter = 0, m = 0, work_count = 0;
         double t = 0, dx, dy, dt, start_t=0;
         double[][] v;
    Details obDetails = new Details();
         public double[][] solveDomainMethod(Double vAxn, Double vAyn, Double vBxn, Double vByn, Integer nxn, Integer nyn, double dt, Double error1n, Double error2n, double end_tn, int stepsn, Integer kcn, Double u_n[][], Double v_n[][], Double bc1, Double bc2, Double bc3, Double bc4, double u[][]) {       
         double dx2, dy2, err = 1000000;
         v = new double[nxn+1][nyn+1];
         DoublevAxn, Double vAyn, Double vBxn, Double vByn, Integer nxn, Integer nyn, double dt, Double error1n, Double error2n, double end_tn, int stepsn, Integer kcn, double u_n[][], double v_n[][], Double bc1, Double bc2, Double bc3, Double bc4;
    double k[][] = new double [nxn+1][nyn+1]; double kp[][] = new double [nxn+1][nyn+1];
    double kpp[][] = new double [nxn+1][nyn+1]; double dudx[][] = new double [nxn+1][nyn+1];
    double dudy[][] = new double [nxn+1][nyn+1]; double d2udx2[][] = new double [nxn+1][nyn+1];
    double d2udy2[][] = new double [nxn+1][nyn+1]; double dudt[][] = new double [nxn+1][nyn+1];
    double a[][] = new double [nxn+1][nyn+1]; double b[][] = new double [nxn+1][nyn+1];
    double c[][] = new double [nxn+1][nyn+1]; double d[][] = new double [nxn+1][nyn+1];
    double F[][] = new double [nxn+1][nyn+1]; double A[][] = new double [nxn+1][nyn+1];
    double B[][] = new double [nxn+1][nyn+1]; double C[][] = new double [nxn+1][nyn+1];
    double D[][] = new double [nxn+1][nyn+1]; double E[][] = new double [nxn+1][nyn+1];
    double s[][] = new double[nxn+1][nyn+1];
              KDerivatives1 obK1 = new KDerivatives1();
              KDerivatives2 obK2 = new KDerivatives2();
    UDerivatives obU = new UDerivatives();
              CalcPdeCoefficients obPde = new CalcPdeCoefficients();
              CalcFdCoefficients obFd = new CalcFdCoefficients();
              Gs obGs = new Gs();
    dx = obDetails.seg(vBxn, vAxn, nxn);
    dy = obDetails.seg(vByn, vAyn, nyn);
    dx2 = dx*dx;
    dy2 = dy*dy;
    if (bc1 != -999999999) obDetails.initialiceBCDomainL(dx, dy, vAxn, vAyn, bc1, u);
    if (bc2 != -999999999) obDetails.initialiceBCDomainU(dx, dy, vAxn, vAyn, bc2, u);
    if (bc3 != -999999999) obDetails.initialiceBCDomainR(dx, dy, vAxn, vAyn, bc3, u);
    if (bc4 != -999999999) obDetails.initialiceBCDomainD(dx, dy, vAxn, vAyn, bc4, u);
    obDetails.source(dx, dy, vAxn, vAyn, s);
    do {
    ++ newton_iter;
    if (kcn == 1) { 
              obK1.calc_k(u, k);
         obK1.calc_kp(u, kp);
         obK1.calc_kpp(u, kpp);
              } else {
                   obK2.calc_k(u, k);
              obK2.calc_kp(u, kp);
              obK2.calc_kpp(u, kpp);
                   obU.calc_dudx(u, dx, dudx);
              obU.calc_dudy(u, dy, dudy);
                   obU.calc_d2udx2(u, dx2, d2udx2);
                   obU.calc_d2udy2(u, dy2, d2udy2);
              obU.calc_dudt(u, u_n, dt, dudt);
              obPde.calcPdeCoefficientsa(k, a);
              obPde.calcPdeCoefficientsb(kp, dudx, b);
              obPde.calcPdeCoefficientsc(kp, dudy, c);
              obPde.calcPdeCoefficientsd(kp, kpp, dudx, dudy, d2udx2, d2udy2, d);
              obPde.calcPdeCoefficientsF(k, kp, dudx, dudy, d2udx2, d2udy2, dudt, s, F);
              obFd.calcFdCoefficientsA(a, b, dx, dx2, A);
              obFd.calcFdCoefficientsB(a, b, dx, dx2, B);
              obFd.calcFdCoefficientsC(a, c, dy, dy2, C);
              obFd.calcFdCoefficientsD(a, c, dy, dy2, D);
              obFd.calcFdCoefficientsE(a, d, dx2, dy2, dt, E);
              obGs.gsMethod(v_n, A, B, C, D, E, F, dt, error2n, v);
              m = m + obGs.iter;
              for (int i=1; i < u.length - 1;i++ ) {
                   for (int j=1; j < u[0].length - 1 ;j++ ) {
         u[i][j] = u[i][j] + v[i][j];
    err = 0;
              for (int i=0; i < u.length ;i++ ) {
                   for (int j=0; j < u[0].length ;j++ ) {
                   err = err + Math.pow(v[i][j],2);
              err = Math.sqrt(err);
    while (err > error1n);
         return u;           
    public double[][] rectangleDomainF (Vector vAxvector, Vector vAyvector, Vector vBxvector, Vector vByvector, Vector nxvector, Vector nyvector, Vector error1vector, Vector error2vector, double end_t, int steps, Vector kcvector, double numberdomains, Vector bc1vector, Vector bc2vector, Vector bc3vector, Vector bc4vector) {
                   double u[][] = new double[u.length][u[0].length];
                   double dt = obDetails.seg(end_t, start_t, steps);
                   Vector uvector = new Vector();
                   Vector vvector = new Vector();
         do
    ++work_count;
              t = work_count * dt;
    for (int k = 0; k < numberdomains ; k++) {
         solveDomainMethod((Double)vAxvector.elementAt(k), (Double)vAyvector.elementAt(k), (Double)vBxvector.elementAt(k), (Double)vByvector.elementAt(k), (Integer)nxvector.elementAt(k), (Integer)nyvector.elementAt(k), dt, (Double)error1vector.elementAt(k), (Double)error2vector.elementAt(k), end_t, steps, (Integer)kcvector.elementAt(k), (Double [][]) uvector.elementAt(k), (Double [][]) vvector.elementAt(k), (Double)bc1vector.elementAt(k), (Double)bc2vector.elementAt(k), (Double)bc3vector.elementAt(k), (Double)bc4vector.elementAt(k), u);
                                                           uvector.insertElementAt(u, k);
              vvector.insertElementAt(v, k);
    while (t < end_t);
    return u;

    The only way to, for instance, multiply a Double object by another Double object is to convert them back to primitives, multiply them, and create a new Double instance:
    public Double multiply(Double lhs, Double rhs) {
       return new Double( lhs.doubleValue() * rhs.doubleValue() );
    }This is just an overhead that you have to accept if you want to use collections with primitive type data.
    Coming soon in 1.5 (which is in Beta now and available for download in the usual places) a new feature called auto-boxing will do a lot of this automatically for you. You need to be aware that it's doing exactly the same operations with the same performance overhead; but it does save a lot of typing.
    Thus in 1.5 the above becomes:
    public Double multiply(Double lhs, Double rhs) {
       // Under the hood this is IDENTICAL to the above example
       return lhs * rhs;
    }Now, addressing your post directly:
    Besides I cant turn a data from "Double" to "double"
    Yes you can, as in the first example, the doubleValue() method converts a Double object to a double primitive.
    Java is not very useful to do this numerical problem.
    If you need math performance, you need to use primitives, yes. Yes, that will preclude the use of collections.
    Dave.

Maybe you are looking for

  • Calling Web Service with SOAP header from BPEL

    Hi, I am calling a web service (with header information) from BPEL. In the Invoke activity, i created a header variable to pass the header information. But, when i test the BPEL service, invoke activity fails because the header information is not bei

  • How to ChangePlantfor each item of Sales order using User Exit SAVE_DOCUMEN

    Hi All, I have to change plant for Each line item of sales order using (MV45AFZZ) (USEREXIT_SAVE_DOCUMENT) based on first Schedule line. if Confirmed Quantity is Less than Ordered Quantity. based on first Schedule line. it has to select other Plant a

  • Save an edited picture as new

    Hi! I have a simple question (I think). I have edited some pictures in iPhoto '11 and would like to have them as a standard .jpg or whatever. How do I do? Jonas

  • Garmin App not Working with Dock Connector in Ford Flex

    I'm having an issue getting the Garmin N American iPhone App to send its turn by turn directions to Sync in my 2010 Ford Flex. I realize that I'm dealing with 3 technologies, Microsoft Sync, iOS in iPhone 4S and Garmin App. So I'm posting to 3 forums

  • Batch input session for 'MB1C' is different from TC 'MB1C'

    hi all,        I processed my bdc in sm35 in 'process/foreground' mode , and I find the screen is different from front-end screen. what's wrong? In 'SHDB', I already click the 'not a batch input session' checkbox.