?
Solved

What would be the java equivalent code for setting up this array (originally programmed in php)?

Posted on 2009-02-23
36
Medium Priority
?
480 Views
Last Modified: 2012-05-06
Hi,

I have some php code, which essentially takes 3 values from a database and assigns them into an array called sharearray.

This then allows the contents (sharedata_ID, shareName and rawKvalue) to be found within the array (rather like making a searchable recordset I guess).

My question is, how would I write the code below

// THIS IS THE BIT I'M INTERESTED IN

in Java? I want to be able to reference the array in teh same way i.e.

//my piguon code
System.out.println(sharearray[2]["rawKvalue"]);

Thanks
James

// select ALL data for THIS share (including non trading days as we're doing WEEKLY data)
// select ALL data for THIS share (but ONLY selecting TRADING DAYS)
$sqlquery = "SELECT sharedata_ID from sharedata WHERE ShareName='$ShareName'";
$result = mysql_query($sqlquery);
$rowcount = mysql_num_rows($result);
$row = mysql_fetch_array($result);
$firstrecord = $row['sharedata_ID'];
 
if ($rowcount==1){$lastrecord=$firstrecord;}else{
while($row = mysql_fetch_array($result)){$lastrecord = $row['sharedata_ID'];}}
 
 
//echo "<BR>First record ".$firstrecord;
//echo "<BR>Last record ".$lastrecord;
 
 
$sqlquery = "SELECT * from sharedata WHERE ShareName='$ShareName'";
$result = mysql_query($sqlquery);
$rowcount = mysql_num_rows($result);
 
// THIS IS THE BIT I'M INTERESTED IN
$i=$firstrecord;
while($row = mysql_fetch_array($result)) {
	// make and array of all results	
	$sharearray[$i]["sharedata_ID"] = $row['sharedata_ID'];
	$sharearray[$i]["ShareName"] = $row['ShareName'];
	$sharearray[$i]["rawKvalue"] = "";
	$i += 1;
}

Open in new window

0
Comment
Question by:JamesFrog
  • 15
  • 14
  • 7
36 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 23709654
Java doesn't have associative arrays (one way it differs from JavaScript). It does, however, have Map, so you can use one. Or you could use Lists.

I notice you select * yet only use 3 columns - is that right?
0
 

Author Comment

by:JamesFrog
ID: 23709676
"I notice you select * yet only use 3 columns - is that right?" - It's bad code I know.. :-)

Please could you show me some Java of how to do this please.
0
 

Author Comment

by:JamesFrog
ID: 23709686
PS. I don't mind if it's not associative - just that it does the equivalent then..
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 23709740
If you want to save a ResultSet, i would use the following approach: you can access it by index, as opposed to name:

http://technojeeves.com/joomla/index.php/free/68-resultset-to-nested-list
0
 

Author Comment

by:JamesFrog
ID: 23709766
If I understand the code correctly, is that creating an ArrayList?

I've heard they're not as quick as normal arrays - is that true? Do you feel an ArrayList is the best way forward with this task?

Thanks
J
0
 
LVL 92

Expert Comment

by:objects
ID: 23709794
Write your self a little bean class to store the details from each row

\eg.
public class ShareData
{
   int id;
   String name;
   String value;
...
0
 
LVL 92

Expert Comment

by:objects
ID: 23709801
you can then use a List to store the elements from the result set
though a Map (or Set) may be more apprriote allowing you to lookup ShareData by id or name

eg.  Map

0
 

Author Comment

by:JamesFrog
ID: 23709804
... the Bean class idea is probably a bit to advanced for me? Can you be clearer with your code on how to do this?... wouldn't the array list be simplers?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 23709813
>>I've heard they're not as quick as normal arrays - is that true?

Yes, theoretically, but an ArrayList is backed by an array and as fast as you can get practicably. It's very fast, and faster than anything else suggested so far
0
 
LVL 92

Expert Comment

by:objects
ID: 23709814
PreparedStatement ps = connection.prepareStatement("SELECT  from sharedata_ID, ShareName WHERE ShareName=?");
ps.setObject(1, shareName);
ResultSet rs = ps.executeQuery();

Map data = new HashMap();
List list = new ArrayList();
while (rs.next())
{
   ShareData sd = new ShareData(rs.getInteger(1), rs.getString(2));
   data.put(sd.getId(), sd);
   list.add(sd);
}
rs.close();
ps.close();

0
 
LVL 92

Expert Comment

by:objects
ID: 23709816
that shows how to use a List and a Map
let me know if you have any questions

0
 

Author Comment

by:JamesFrog
ID: 23709828
...it's worth mentioning that this array will then be manipulated so that values within the array (missing data in rows of the database) will be added...

i.e.

1
NULL
2
NULL
5
NULL
10

will become (after processing)

1
1.5
2
3.5
5
7.5
10

can this be done with array lists?
0
 
LVL 92

Expert Comment

by:objects
ID: 23709831
And if you wanted an array you'd add

ShareData[] array = list.toArray(new ShareData[0]);

so you could then access the array using:

ShareData s = array[0];

0
 
LVL 92

Expert Comment

by:objects
ID: 23709838
> ...it's worth mentioning that this array will then be manipulated so that values within the array (missing data in rows of the database) will be added...

yes you'd just add another property to the bean class.

eg. to add  value property you'd add

   private Object value;
   public Object getValue() { return value; }
   public void setValue(Obect value) { this.value = value; }

nice and easy :)

0
 

Author Comment

by:JamesFrog
ID: 23709912
Savant,

I have to say I am a little bit confused how to put this all together so perhaps you enlighten me.

The my real resultset code is

ResultSet resultset = statement.executeQuery("SELECT TradingDayNumber K332d FROM Xsharedata WHERE ShareName=RIO);

Here is a demonstration output

sharedata_ID | K332d

5                     | 20
6                     | NULL
7                     | 30
8                     | NULL
9                     | 33
10                   | NULL
11                   | NULL
12                   | 36
13                   | NULL
14                   | 40
15                   | NULL
16                   | 80

Now I'd want my code to go through this array filling in all the details as if to make a straight line between the points, so the above would return

sharedata_ID | K332d

5                     | 20
6                     | 25
7                     | 30
8                     | 32
9                     | 33
10                   | 34
11                   | 35
12                   | 36
13                   | 38
14                   | 40
15                   | 60
16                   | 80

The contents of this array would then be fed back into the database table (i.e. to fill in the gaps).

Note: sometimes there may be different amounts of NULL values before the next K332d value.

Please could you write clear executable code to do this, because then I'll be able to see how all this fits together.

Thanks
J
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 23709919
>>1
NULL
2
NULL
5
NULL
10

will become (after processing)

1
1.5
2
3.5
5
7.5
10

can this be done with array lists?
>>

Yes, couldn't be easier:
 
listOfLists.get(1).add(0, 1.5);
listOfLists.get(3).add(0, 3.5);
//etc

Open in new window

0
 

Author Comment

by:JamesFrog
ID: 23709921
PS. I meant

TradingDayNumber | K332d

not

sharedata_ID | K332d
0
 

Author Comment

by:JamesFrog
ID: 23709935
CEHJ, could you show me code of how to do this with ArrayLists's as well - I'm interested to see the whole working code with Savants and your method to compare how they work in practice...

I will split the points equally after I've tested the solutions.

Thanks
James
0
 
LVL 92

Accepted Solution

by:
objects earned 1500 total points
ID: 23709937
try something like this:

PreparedStatement ps = connection.prepareStatement("("SELECT TradingDayNumber K332d FROM Xsharedata WHERE K332d is not NULL and ShareName=?");
ps.setObject(1, "RIO");
ResultSet rs = ps.executeQuery();

String[] data = new String[MAX];
while (rs.next())
{
   int id = rs.getInt(1);
   String name = rs.getString(2);
   data[id] = name;
}
rs.close();
ps.close();

0
 
LVL 92

Expert Comment

by:objects
ID: 23709948
you can then access a nem using:

String name = data[index];

0
 
LVL 92

Expert Comment

by:objects
ID: 23709959
you'd only use an ArrayList if you didn't know the size of the array needed (which is pretty easy to work out).

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 23710005
>>(which is pretty easy to work out)

You can't 'work it out' ;-) You can only *find out* by issuing another query against the db, and i can assure you that cost is not worth the difference in weight between an array and an ArrayList
0
 

Author Comment

by:JamesFrog
ID: 23710024
Savant,

I do know the size of the array, as it's the recordset size - so I'm guessing I don't need the ArrayList - so please could you show me the full code to achieve what I need to achieve (see previous post by me) - as this is the only way I can learn easily (when I see code in full context of the task I need to achieve). I then find it easy to extrapolate this knowledge to do anything required with the method you're suggesting.

Thanks
J
0
 
LVL 92

Expert Comment

by:objects
ID: 23710030
you wouldn't need to make another query to the database. One is sufficient

0
 
LVL 92

Expert Comment

by:objects
ID: 23710039
u wouldn't need an ArrayList if you didn't know the size needed :)
I already posted the required code earlier

PreparedStatement ps = connection.prepareStatement("("SELECT TradingDayNumber K332d FROM Xsharedata WHERE K332d is not NULL and ShareName=?");
ps.setObject(1, "RIO");
ResultSet rs = ps.executeQuery();

String[] data = new String[MAX];
while (rs.next())
{
   int id = rs.getInt(1);
   String name = rs.getString(2);
   data[id] = name;
}
rs.close();
ps.close();

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 23710063
>>as it's the recordset size

I thought you were doing this in Java - how do you know the recordset size?
0
 

Author Comment

by:JamesFrog
ID: 23710092
By using the method

public static int getResultSetSize(ResultSet resultSet) {
          int size = -1;

          try {
              resultSet.last();
              size = resultSet.getRow();
              resultSet.beforeFirst();
          } catch(SQLException e) {
              return size;
          }

          return size;
      }
0
 

Author Comment

by:JamesFrog
ID: 23710102
I'm now very confused.

... should I use ArrayList or the other method? Or is there no CLEAR answer to this?

I am a novice Java programmer, which one would be easier for me to get to grips with?

Thanks
J
0
 
LVL 92

Expert Comment

by:objects
ID: 23710112
its very clear here :) an ArrayList offers you nothing. It'll just be slower.
An array will do everything you need and its faster.

0
 

Author Comment

by:JamesFrog
ID: 23710121
So please objects, could you provide full code to achieve the following

---------
ResultSet resultset = statement.executeQuery("SELECT TradingDayNumber K332d FROM Xsharedata WHERE ShareName=RIO);

Here is a demonstration output

sharedata_ID | K332d

5                     | 20
6                     | NULL
7                     | 30
8                     | NULL
9                     | 33
10                   | NULL
11                   | NULL
12                   | 36
13                   | NULL
14                   | 40
15                   | NULL
16                   | 80

Now I'd want my code to go through this array filling in all the details as if to make a straight line between the points, so the above would return

sharedata_ID | K332d

5                     | 20
6                     | 25
7                     | 30
8                     | 32
9                     | 33
10                   | 34
11                   | 35
12                   | 36
13                   | 38
14                   | 40
15                   | 60
16                   | 80

The contents of this array would then be fed back into the database table (i.e. to fill in the gaps).

Note: sometimes there may be different amounts of NULL values before the next K332d value.

Please could you write clear executable code to do this, because then I'll be able to see how all this fits together.

Thanks
J-
---------------------------
0
 

Author Comment

by:JamesFrog
ID: 23710131
sorry, again I meant

TradingDayNumber | K332d

not

sharedata_ID | K332d

in the table details anove
0
 
LVL 92

Expert Comment

by:objects
ID: 23710157
for (int i=0; i
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 23710187
>>By using the method

That's a very expensive way of finding out (especially when you don't need to). A better way to do it if you *did* need to would be to select count(*)
0
 

Author Comment

by:JamesFrog
ID: 23710929
... I'm just studying the HashMap thing at the moment...
0
 

Author Closing Comment

by:JamesFrog
ID: 31549992
Thanks for your efforts on this one. The code I finally wrote based on these ideas is below and seems to work just fine.

int[] tradingDayNumberArray = new int[sizeOfResultSet+1];
                     double[] K322dArray = new double[sizeOfResultSet+1];
                     int arrayCounter=1;
                     
                     while (resultset.next())
                     {
                       // int id = resultset.getInt(1);
                        int tradingDayNumber = resultset.getInt(1);
                        System.out.println(tradingDayNumber);
                        tradingDayNumberArray[arrayCounter] = tradingDayNumber;
                        
                        double K322value = resultset.getDouble(2);
                        K322dArray[arrayCounter] = K322value;
                        System.out.println(resultset.getDouble(2));
                        
                     arrayCounter++;
                     }
                     resultset.close();
0
 
LVL 92

Expert Comment

by:objects
ID: 23716556
> ... I'm just studying the HashMap thing at the moment...

for what you are doing you don't need a Map. A Map would only be useful in your case if you want to be able to look up an id by value

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month15 days, 4 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question