473,804 Members | 2,255 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array in ArrayList

3 New Member
I have a ArrayList which I add a Array to. How will I access the array from the ArrayList?

Example :

/*Storing the array*/
String[] Container = new String[3];
ArrayList arr =new ArrayList();
ResultSet rec1 = st.executeQuery ("SELECT * FROM HistoryHeader WHERE DocumentDate BETWEEN '"+startDate +"' AND '"+endDate+"'") ;
while(rec1.next ()) {
Container[0] = rec1.getString( "DocumentType") ;
Container[1] = rec1.getString( "DocumentNumber ");
Container[2] = rec1.getString( "CustomerCode") ;
arr.add(Contain er);
}

/*Viewing the String Array from the Array list*/
I want to access the array like arr.get(1)[1]
So get element 1 from the stored array from the first ArrayList element.

Whats the syntax for this?
Mar 7 '08 #1
7 2106
JosAH
11,448 Recognized Expert MVP
Your code is so wrong: you load the content of each record (three columns) in
the same Container over and over again and you add that Container to your list
over and over again so you end up with n copies of your Container array in your
list and it contains the data from the last row read from your database. (you have
overwritten any previous content in that Container array).

But there is more: why don't you build a simple class that represents the data
from a single row? Construct an object from that class for each row read and
add the objects for your list.

kind regards,

Jos
Mar 7 '08 #2
jingles
2 New Member
I have a ArrayList which I add a Array to. How will I access the array from the ArrayList?

Example :

/*Storing the array*/
String[] Container = new String[3];
ArrayList arr =new ArrayList();
ResultSet rec1 = st.executeQuery ("SELECT * FROM HistoryHeader WHERE DocumentDate BETWEEN '"+startDate +"' AND '"+endDate+"'") ;
while(rec1.next ()) {
Container[0] = rec1.getString( "DocumentType") ;
Container[1] = rec1.getString( "DocumentNumber ");
Container[2] = rec1.getString( "CustomerCode") ;
arr.add(Contain er);
}

/*Viewing the String Array from the Array list*/
I want to access the array like arr.get(1)[1]
So get element 1 from the stored array from the first ArrayList element.

Whats the syntax for this?

You are on the right lines. However, the problem is that when you retrieve your String[] from your ArrayList using the .get(index) method, your String[] will be returned as an Object. If you are using an IDE like Eclipse or NetBeans it should tell you the type of the object that is being returned.

You have two options to solve this problem;

1. Cast the object being returned back to a String[].

So for example:
Expand|Select|Wrap|Line Numbers
  1. String[] myArray = (String[])arr.get(1);
  2. System.out.println(myArray[0]);
  3.  
If you choose this approach, you should ensure that checks are made that the object being returned is actually a String[] before you get it, otherwise exceptions will be thrown when you recast the object. You can do this using the "instanceof " operator.


2. Make use of the ArrayList class' generics feature.

Many of the classes in the java.util package are "generic". This means that you can specify the type of object that they deal with. They will then provide type safety when you are adding and retrieving objects from the class. You can specify an ArrayList to contain String[]'s like so:

Expand|Select|Wrap|Line Numbers
  1. ArrayList<String[]> myArrayList = new ArrayList<String[]>();
The type in between the < and > symbols specifies the type the ArrayList can handle. Once you have an instance of an ArrayList of this specification; your original code will work:

Expand|Select|Wrap|Line Numbers
  1. arr.get(1)[1]; 
This is because the get(index) method now knows that it should return the type of String[] rather than Object.

Generics are very useful. You can read more about them here .
Mar 7 '08 #3
Unite
3 New Member
You sir are my hero. Worked like a charm. Thank you very much.

You are on the right lines. However, the problem is that when you retrieve your String[] from your ArrayList using the .get(index) method, your String[] will be returned as an Object. If you are using an IDE like Eclipse or NetBeans it should tell you the type of the object that is being returned.

You have two options to solve this problem;

1. Cast the object being returned back to a String[].

So for example:
Expand|Select|Wrap|Line Numbers
  1. String[] myArray = (String[])arr.get(1);
  2. System.out.println(myArray[0]);
  3.  
If you choose this approach, you should ensure that checks are made that the object being returned is actually a String[] before you get it, otherwise exceptions will be thrown when you recast the object. You can do this using the "instanceof " operator.


2. Make use of the ArrayList class' generics feature.

Many of the classes in the java.util package are "generic". This means that you can specify the type of object that they deal with. They will then provide type safety when you are adding and retrieving objects from the class. You can specify an ArrayList to contain String[]'s like so:

Expand|Select|Wrap|Line Numbers
  1. ArrayList<String[]> myArrayList = new ArrayList<String[]>();
The type in between the < and > symbols specifies the type the ArrayList can handle. Once you have an instance of an ArrayList of this specification; your original code will work:

Expand|Select|Wrap|Line Numbers
  1. arr.get(1)[1]; 
This is because the get(index) method now knows that it should return the type of String[] rather than Object.

Generics are very useful. You can read more about them here .
Mar 7 '08 #4
JosAH
11,448 Recognized Expert MVP
You sir are my hero. Worked like a charm. Thank you very much.
If you go this path you end up with a very non object oriented solution. Have you
tested your 'solution' with multiple arrays yet?

kind regards,

Jos
Mar 7 '08 #5
BigDaddyLH
1,216 Recognized Expert Top Contributor
If you go this path you end up with a very non object oriented solution. Have you
tested your 'solution' with multiple arrays yet?

kind regards,

Jos
I agree with Jos. Your code smell is called "object denial". You need to start defining classes that represent your data.
Mar 7 '08 #6
karthickkuchanur
156 New Member
I have a ArrayList which I add a Array to. How will I access the array from the ArrayList?

Example :

/*Storing the array*/
String[] Container = new String[3];
ArrayList arr =new ArrayList();
ResultSet rec1 = st.executeQuery ("SELECT * FROM HistoryHeader WHERE DocumentDate BETWEEN '"+startDate +"' AND '"+endDate+"'") ;
while(rec1.next ()) {
Container[0] = rec1.getString( "DocumentType") ;
Container[1] = rec1.getString( "DocumentNumber ");
Container[2] = rec1.getString( "CustomerCode") ;
arr.add(Contain er);
}

/*Viewing the String Array from the Array list*/
I want to access the array like arr.get(1)[1]
So get element 1 from the stored array from the first ArrayList element.

Whats the syntax for this?
try it
arrayFetch.toAr ray(arrFinance) ;
Mar 8 '08 #7
JosAH
11,448 Recognized Expert MVP
try it
arrayFetch.toAr ray(arrFinance) ;
What object or class is 'arrayFetch'? What does its 'toArray' method do? What is
the 'arrFinance' variable? Are you sure you put your reply in the correct thread?

kind regards,

Jos
Mar 8 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
21883
by: davehunt | last post by:
Hi folks, New C# programmer here. I am reading some CSV data from a file into an ArrayList. I want to get the data from the ArrayList into a 2-dimensional array. I see a few references to ..Split, but I'm not sure that's what I need. So, basically, what I have loaded into the ArrayList is:
13
11324
by: Hrvoje Voda | last post by:
How to put a specified dataset table into an array list ? Hrcko
9
1593
by: Steve | last post by:
Hello, I created a structure ABC and an array of type ABC Public Structure ABC Dim str1 As String Dim int1 As Integer End Structure Public ABC1 As New ABC, ABC2 As New ABC
4
2829
by: Peter | last post by:
I run into this situation all the time and I'm wondering what is the most efficient way to handle this issue: I'll be pulling data out of a data source and want to load the data into an array so that I can preform complicated operations against this data. The returned record count in these operations is always variable. 1. I have been using an arraylist.add function to handle non-multidemional returns but was wondering if I'm better...
5
19604
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return an Array instead of an ArrayList. Now I get the message when I try to run just my webservice...
18
3259
by: Sam | last post by:
Hi All I'm planing to write an application which allows users dynamically add their points (say you can add upto 30,000) and then draw xy graph. Should I use an array for my coordinate point storage and dynamically resize it when there is a new point or should I use ArrayList? Is speed noticable between the two? Regards,
24
4410
by: RyanTaylor | last post by:
I have a final coming up later this week in my beginning Java class and my prof has decided to give us possible Javascript code we may have to write. Problem is, we didn't really cover JS and what we covered was within the last week of the class and all self taught. Our prof gave us an example of a Java method used to remove elements from an array: public void searchProcess() { int outIt=0;
5
28400
by: Paulers | last post by:
Hello all, I have a string array with duplicate elements. I need to create a new string array containing only the unique elements. Is there an easy way to do this? I have tried looping through each element but I am having issues using redim to adjust the new array. Any help or example code would be greatly appreciated. thanks!
12
14460
by: Maxwell2006 | last post by:
Hi, I declared an array like this: string scriptArgs = new string; Can I resize the array later in the code? Thank you, Max
9
5688
by: Brian Tkatch | last post by:
I'm looking for a simple way to unique an array of strings. I came up with this. Does it make sense? Am i missing anything? (Testing seems to show it to work.) Public Function Unique(ByVal List() As String) As String() ' Returns the unique values of in array, in an array. Dim Temp As New System.Collections.Specialized.StringCollection()
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10346
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5531
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.