Hi and I have been working on a simple problem but can't seem to find any solution and have tried browsing the net. My question is how do I append to an array. Below is the code I tried but still doesn't work.

String[] names={""};
            if (charcheck1==true) {
                String[] chartmp={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
                for (int j=0;j<chartmp.length;j++) {
                    names[names.length]=chartmp[j];
                }
            }
            if (charcheck2==true) {
                String[] chartmp={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
                for (int j=0;j<chartmp.length;j++) {
                    names[names.length]=chartmp[j];
                }
            }
            if (charcheck3==true) {
                String[] chartmp={"1","2","3","4","5","6","7","8","9","0"};
                for (int j=0;j<chartmp.length;j++) {
                    names[names.length]=chartmp[j];
                }
            }
            if (charcheck4==true) {
                String[] chartmp={"`","~","!","@","#","$","%","^","&","*","(",")","-","_","+","=","|","\\","[","{","]","}",";",":","'","\"",",","<",".",">","?","/"," "};
                for (int j=0;j<chartmp.length;j++) {
                    names[names.length]=chartmp[j];
                }
            }

According to several sites I was browsing the above code should work but for some reason doesn't and reports a java.lang.ArrayIndexOutOfBoundsException: 1 error. Does anybody know how I can append to the array and please keep it simple as I am just beginning to learn Java? Thanks.

peter_budo commented: Interesting question +11

Recommended Answers

All 16 Replies

Interesting behaviour, I was thinking that repeated assignment in this scenario is fine as basically this should repeatedly overwrite that single object of names array. We will have wait and see if anyone knows...

Isn't this suppose to throw an ArrayIndexOutOfBounds Exception?:

names[names.length] = ...

names's length is 1 java.lang.ArrayIndexOutOfBoundsException: [B]1[/B]

> Does anybody know how I can append to the array

You can't. The best you can do is perform a copy-on-write if the content to be written is more than the initial capacity with which the array was created. Try using an implementation like ArrayList which relieves you of all this resizing business. Is there any specific requirement you are trying to fulfill which can't utilize better data structures?

LOL, I guess I should not be replying to threads when I get out of the bed...

>Is there any specific requirement you are trying to fulfill which can't utilize better data structures?

If you mean is there any better design I could follow without appending then I'm am not exactly sure because basically I have 4 tickboxes in the gui and when one is ticked the variable in the if statements changes to true. The tricky part is that the result is a complete array and the tickboxes selects what parts of the array should exist in other words different tickbox combinations will result in different arrays. Are there any examples on how I can do this?

Sadly, this simple a thing becomes pretty clunky to implement when it comes to Java. A sample implementation might be something like:

class YourClass {
   
   private static final List<String> LOWER_CASE_CHARS;
   
   private static final List<String> UPPER_CASE_CHARS;
   
   static {
      LOWER_CASE_CHARS = listFromArray("abcdefgh".toCharArray());
      UPPER_CASE_CHARS = listFromArray("ABCDEFGH".toCharArray());
   }
   
   private static List<String> listFromArray(char[] charArray) {
      List<String> list = new ArrayList<String>(charArray.length);
      for(char ch : charArray) {
         list.add(String.valueOf(ch));
      }
      return list;
   }
   
   public String[] fillResultArray() {
      boolean checkBoxOneChecked = true, checkBoxTwoChecked = true;
      List<String> stringList = new ArrayList<String>();
      if(checkBoxOneChecked) {
         stringList.addAll(LOWER_CASE_CHARS);
      }
      if(checkBoxTwoChecked) {
         stringList.addAll(UPPER_CASE_CHARS);
      }
      return stringList.toArray(new String[] {});
   }
   
}

Does that work out for you?

commented: great code snippet... +4

Does that work out for you?

It's hard to see how that code works or if it works but although I check some more documentation, is it possible to loop through the contents of two arrays to populate a third array with the combined content?

It's hard to see how that code works or if it works but although I check some more documentation, is it possible to loop through the contents of two arrays to populate a third array with the combined content?

Yes

> is it possible to loop through the contents of two arrays to populate a
> third array with the combined content?

In my code I'm using looping through two Lists and populating a third list which is then converted to an array and returned.

Sadly, this simple a thing becomes pretty clunky to implement when it comes to Java. A sample implementation might be something like:

class YourClass {
   
   private static final List<String> LOWER_CASE_CHARS;
   
   private static final List<String> UPPER_CASE_CHARS;
   
   static {
      LOWER_CASE_CHARS = listFromArray("abcdefgh".toCharArray());
      UPPER_CASE_CHARS = listFromArray("ABCDEFGH".toCharArray());
   }
   
   private static List<String> listFromArray(char[] charArray) {
      List<String> list = new ArrayList<String>(charArray.length);
      for(char ch : charArray) {
         list.add(String.valueOf(ch));
      }
      return list;
   }
   
   public String[] fillResultArray() {
      boolean checkBoxOneChecked = true, checkBoxTwoChecked = true;
      List<String> stringList = new ArrayList<String>();
      if(checkBoxOneChecked) {
         stringList.addAll(LOWER_CASE_CHARS);
      }
      if(checkBoxTwoChecked) {
         stringList.addAll(UPPER_CASE_CHARS);
      }
      return stringList.toArray(new String[] {});
   }
   
}

Does that work out for you?

I managed to get that example working except for the final array doesn't start with the first value being blank/empty. I have been trying to find a way to get a blank value as the first value on the array but do you know of any quick way of doing it as I am still trying to find how to add that final value. An example of what I tried is as follows:

BLANK_CHAR = listFromArray("".toCharArray());

But the above line doesn't work. :( Please help. Thanks.

[edit]
Just discovered the following code which now seems to work. Hopefully it should be solved soon.

stringList.add("");

[/edit]

Hi and although I have solved the previous array problem I am struggling to find how to get the current timestamp (seconds since 1970). Below is two scripts I have tried unsuccessfully.

java.sql.Timestamp ts = new java.sql.Timestamp((new java.util.Date()).getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse(ts); // parse date
long timestart = d.getTime();

//the above was one script and the below is another

Timestamp timestart = Timestamp.valueOf("ss");

Does anybody know how to get the current timestamp as an integre as I can't find a single site with the answer? Thanks for the great helps so far.

What's wrong with the getTime() method of the Date class which returns the number of milliseconds elapsed since January 1970 as long? To get the seconds, just divide by 1000.

I have managed to piece together the below code but still it doesn't work. According to my compiler it cannot find symbol and the symbol is the Date() constructor. Also the Date() constructor has a red underline in my compiler meaning there is something wrong with it which I can't exactly get my head around. Can you see what's wrong with the below code?

public static long gettimestamp() {
    Date data = new Date();
    return (data.getTime()/1000);
    }

You need to use java.util.Date, not java.sql.Date.

If you mean is there any better design I could follow without appending then I'm am not exactly sure because basically I have 4 tickboxes in the gui and when one is ticked the variable in the if statements changes to true. The tricky part is that the result is a complete array and the tickboxes selects what parts of the array should exist in other words different tickbox combinations will result in different arrays. Are there any examples on how I can do this?

I see that you have solved this part already, but I thought I would add a couple of examples of different designs you can use for that.

This one uses a small listener class that takes the list you want to append as a parameter. To map the check box, you create and add one of these listeners with the list you want to associate with that box. See the comments for clarification

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CheckboxDemo {
    JCheckBox box1;
    JCheckBox box2;
    JCheckBox box3;
    JTextArea output;

    // the lists we will map to the check boxes
    List<String> list1 = new ArrayList<String>(Arrays.asList(new String[]{"a","b","c"}));
    List<String> list2 = new ArrayList<String>(Arrays.asList(new String[]{"1","2","3"}));
    List<String> list3 = new ArrayList<String>(Arrays.asList(new String[]{"x","y","z"}));

    // this will hold the "final" list that results from clicks
    List<String> resultList = new ArrayList<String>();

    public CheckboxDemo() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel top = new JPanel();
        box1 = new JCheckBox("1");
        // each box gets a different listener
        box1.addActionListener( new MappedCheckboxListener(list1) );
        box2 = new JCheckBox("2");
        box2.addActionListener( new MappedCheckboxListener(list2) );
        box3 = new JCheckBox("3");
        box3.addActionListener( new MappedCheckboxListener(list3) );

        top.add(box1);
        top.add(box2);
        top.add(box3);

        JPanel bottom = new JPanel();
        output = new JTextArea();
        bottom.add(output);

        frame.add(top,BorderLayout.NORTH);
        frame.add(bottom,BorderLayout.CENTER);

        frame.setVisible(true);
    }

    class MappedCheckboxListener implements ActionListener{
        List<String> list;

        public MappedCheckboxListener(List<String> associatedList){
            this.list = associatedList;
        }

        public void actionPerformed(ActionEvent e) {
            JCheckBox clickedBox = (JCheckBox)e.getSource();
            if (clickedBox.isSelected()){
                resultList.addAll(list);
            } else {
                resultList.removeAll(list);
            }
            output.setText(resultList.toString());
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                CheckboxDemo d = new CheckboxDemo();
            }
        });
    }
}

The next one is very similar, but uses a Map to establish the link between the check box and its list. There is a single action listener that updates the result list based upon which box is clicked.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CheckboxDemo implements ActionListener{
    JCheckBox box1;
    JCheckBox box2;
    JCheckBox box3;
    JTextArea output;

    // the lists we will map to the check boxes
    List<String> list1 = new ArrayList<String>(Arrays.asList(new String[]{"a","b","c"}));
    List<String> list2 = new ArrayList<String>(Arrays.asList(new String[]{"1","2","3"}));
    List<String> list3 = new ArrayList<String>(Arrays.asList(new String[]{"x","y","z"}));

    // this will hold the "final" list that results from clicks
    List<String> resultList = new ArrayList<String>();

    // holds the mappings of check boxes to their lists
    Map <JCheckBox,List> checkMap = new HashMap<JCheckBox, List>();

    public CheckboxDemo() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel top = new JPanel();
        box1 = new JCheckBox("1");
        // all boxes share a common listener
        box1.addActionListener(this);
        box2 = new JCheckBox("2");
        box2.addActionListener(this);
        box3 = new JCheckBox("3");
        box3.addActionListener(this);

        // build our mappings
        checkMap.put(box1, list1);
        checkMap.put(box2, list2);
        checkMap.put(box3, list3);

        top.add(box1);
        top.add(box2);
        top.add(box3);

        JPanel bottom = new JPanel();
        output = new JTextArea();
        bottom.add(output);

        frame.add(top,BorderLayout.NORTH);
        frame.add(bottom,BorderLayout.CENTER);

        frame.setVisible(true);
    }

    // action listener impl
    public void actionPerformed(ActionEvent e) {
        // add or remove the list for this box based on selection
        JCheckBox clickedBox = (JCheckBox)e.getSource();
        List selectedList = checkMap.get(clickedBox);
        if (clickedBox.isSelected()){
            resultList.addAll(selectedList);
        } else {
            resultList.removeAll(selectedList);
        }
        output.setText(resultList.toString());
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                CheckboxDemo d = new CheckboxDemo();
            }
        });
    }

}

You need to use java.util.Date, not java.sql.Date.

Found the bug. I used the wrong import method thanks to user javaAddict for pointing out about util instead of sql. Now my application is running perfectly and *solved*

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.