3

How can we use Arrays and ArrayLists together (if possible at all)?

I want to store some Strings into an ArrayList, pull them out later, parse them up into String arrays, store those arrays in an ArrayList, and be able to retrieve the data from the ArrayLists later...

Check out this code, and feel free to take me apart for doing crappy coding; it's been a while since I used Java.

public static void parseData() throws IOException
{
    //for reference, nonParsedData is ArrayList<String>
    // while parsedData is ArrayList<String[]>
    String line = new String();
    String[] tempContainer = new String[7];
    Scanner keyboard = new Scanner(System.in);

    for (int x = 0; x < nonParsedData.size(); x++)
    {
        line = nonParsedData.get(x);

        //filling the temporary container to place into the ArrayList of arrays
        tempContainer[0] = line.substring(0,1); //Data piece 1
        tempContainer[1] = line.substring(1,3); //Data piece 2
        tempContainer[2] = line.substring(3,7); //Data piece 3
        tempContainer[3] = line.substring(7,8); //Data piece 4
        tempContainer[4] = line.substring(8,9); //Data piece 5
        tempContainer[5] = line.substring(9,10); //Data piece 6
        tempContainer[6] = line.substring(10,(line.length() - 1)); //Data piece 7



        parsedData.add(tempContainer);
    }
}

So in the previous, I've dumped some external file into nonParsedData. It's a bunch of strings. No big deal. I take those strings, read them, drop them into arrays. Hunky dory. That works fine.

Here is the retrieval process, which is making me apoplectic.

public static void fetchAndPrint() throws IOException
{
    String[] tempContainer = new String[7];

    for(int x = 0; x < parsedData.size(); x++)
    {

        tempContainer = parsedData.get(x); //this should be assigning my stored array to
                                           //the tempContainer array (I think)

        //let's try deepToString (that didn't work)
        //System.out.println((parsedData.get(x)).toString()); //just a debugging check

        System.out.println(x);
        System.out.println(tempContainer[0] + " " + tempContainer[1] + " " 
            + tempContainer[2] + " " + tempContainer[3] + " " 
            + tempContainer[4] + " " + tempContainer[5] + " " 
            + tempContainer[6] + " ");
    }
}

After I do this, only one of my outputs shows up from the initial ArrayList<String[]> - three times! Am I missing something in my loop? Am I implementing arrays from an ArrayList when there is really no functionality for this? Am I improperly assigning values to an array? Will ArrayList even give me back an actual array - or is it just a list like {1, 2, 3, etc.}? Are these things even different?

Finally, I know this can be implemented using a databasing language, but let's assume I want to stick with Java.

2
  • stackoverflow.com/questions/9929321/… Commented Oct 29, 2014 at 15:58
  • The above post is not what I need, but thanks. The making of the array from ArrayList with strings is fine, it's the retrieving of the arrays once stored that is problematic. Commented Oct 29, 2014 at 16:43

2 Answers 2

1

I'll just keep it simple and answer your question:

How do arraylists and arrays interact with one another in java?

First we have to make distinction between the two.

While arrays (ie. tempContainer[]) are just a collection of like-typed data (primitives or objects) within contiguous memory, ArrayLists are objects with fields and member functions.

Back to your question. In order to convert from an array to an ArrayList:

String[] names = {"Bobby", "Earl", "Super Mario"};
ArrayList<String> namesList = new ArrayList<String>();

// First we must return the array as a List using Arrays.asList()
// Then use the addAll() method provided by the ArrayList class.
namesList.addAll(Arrays.asList(names));

Now for the opposite, returning the contents of an ArrayList into an array:

String[] names;
ArrayList<String> namesList = new ArrayList<String>();

//All that is needed is the ArrayList member method toArray().
names = namesList.toArray();

I hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Raff; it was more about how they act when arrays are placed inside ArrayLists. This is good info though, and appreciated.
0

Because of the scope of tempContainer, you overwrite your values:

String[] tempContainer = new String[7];
for (int x = 0; x < nonParsedData.size(); x++)
{
    line = nonParsedData.get(x);

    //filling the temporary container to place into the ArrayList of arrays
    tempContainer[0] = line.substring(0,1);
    // ...
    parsedData.add(tempContainer); // <=== this is always the same array
}

What you probably want is a brand new array for each iteration like this:

for (int x = 0; x < nonParsedData.size(); x++)
{ 
   String[] tempContainer = new String[7];
   // fill tempContainer
   parsedData.add(tempContainer);

working demo


As a side note you might want to use an object here:

  • Define an object for the parts (lets call it Part)
  • Create a new object for each iteration of the loop
  • Use an ArrayList<Part> for parsedData

6 Comments

So essentially Object Part would be an object containing String[] objects?
or 7 String fields or a List<String>, or something else, it's a matter of taste/preferences
In response to the moving of String[] tempContainer declaration, it does not matter; the output remains...weird. Thanks for the other suggestions though. Will try.
Can you define "weird".
I added a live demo, you probably moved the wrong array declaration. (NB: the demo code is "quick & dirty")
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.