• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 482
  • Last Modified:

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

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
JamesFrog
Asked:
JamesFrog
  • 15
  • 14
  • 7
1 Solution
 
CEHJCommented:
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
 
JamesFrogAuthor Commented:
"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
 
JamesFrogAuthor Commented:
PS. I don't mind if it's not associative - just that it does the equivalent then..
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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.

 
CEHJCommented:
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
 
JamesFrogAuthor Commented:
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
 
objectsCommented:
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
 
objectsCommented:
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
 
JamesFrogAuthor Commented:
... 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
 
CEHJCommented:
>>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
 
objectsCommented:
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
 
objectsCommented:
that shows how to use a List and a Map
let me know if you have any questions

0
 
JamesFrogAuthor Commented:
...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
 
objectsCommented:
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
 
objectsCommented:
> ...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
 
JamesFrogAuthor Commented:
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
 
CEHJCommented:
>>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
 
JamesFrogAuthor Commented:
PS. I meant

TradingDayNumber | K332d

not

sharedata_ID | K332d
0
 
JamesFrogAuthor Commented:
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
 
objectsCommented:
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
 
objectsCommented:
you can then access a nem using:

String name = data[index];

0
 
objectsCommented:
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
 
CEHJCommented:
>>(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
 
JamesFrogAuthor Commented:
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
 
objectsCommented:
you wouldn't need to make another query to the database. One is sufficient

0
 
objectsCommented:
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
 
CEHJCommented:
>>as it's the recordset size

I thought you were doing this in Java - how do you know the recordset size?
0
 
JamesFrogAuthor Commented:
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
 
JamesFrogAuthor Commented:
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
 
objectsCommented:
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
 
JamesFrogAuthor Commented:
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
 
JamesFrogAuthor Commented:
sorry, again I meant

TradingDayNumber | K332d

not

sharedata_ID | K332d

in the table details anove
0
 
objectsCommented:
for (int i=0; i
0
 
CEHJCommented:
>>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
 
JamesFrogAuthor Commented:
... I'm just studying the HashMap thing at the moment...
0
 
JamesFrogAuthor Commented:
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
 
objectsCommented:
> ... 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

  • 15
  • 14
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now