[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 526
  • Last Modified:

HashMap & ArrayList

Well, I've got this little piece of code which I want to print something (described below) on screen.

--- Code ---
import hjelpefiler.KobleTilDB;

import java.sql.*;
import java.util.*;

public class HashMap_Oppg {
      private KobleTilDB db;
      private Connection con;
      
      private Map map;
      
      private String K;
      private Integer antall;
      
      private static String ImporterteVerdier[] = {null};
      
      private HashMap_Oppg(String dbuser, String dbpassw) {
            db = new KobleTilDB(dbuser, dbpassw);
            con = db.getConnection();
            map = new HashMap();
            HentKarakterer();
            
            Set set = map.entrySet();
            Iterator it = set.iterator();
            
            List liste = new ArrayList(Arrays.asList(ImporterteVerdier));
            System.out.println(liste);
            while (it.hasNext()) {
                  System.out.println(it.next());
            } // end while
      } // end method HashMap_Oppg
      
      public static void main(String[] args) {
            new HashMap_Oppg(args[0], args[1]);
      } // end method main
      
      private void HentKarakterer() {
            PreparedStatement pStmt = null;
            ResultSet rs = null;
            int i = 0;
            
            try {
                  pStmt = con.prepareStatement("SELECT snr, karakter FROM eksamen2");
                  rs = pStmt.executeQuery();
                  map.put("A", new Integer( 0 ));
                  map.put("B", new Integer( 0 ));            
                  map.put("C", new Integer( 0 ));                  
                  map.put("D", new Integer( 0 ));            
                  map.put("E", new Integer( 0 ));
                  map.put("F", new Integer( 0 ));
                  while (rs.next()) {
                        K = rs.getString(2);
                        antall = (Integer) map.get(K);
                        if (K.equals("A")) {
                              map.put("A", new Integer(antall.intValue()+1));
                        } else if (K.equals("B")) {
                              map.put("B", new Integer(antall.intValue()+1));            
                        } else if (K.equals("C")) {
                              map.put("C", new Integer(antall.intValue()+1));                  
                        } else if (K.equals("D")) {
                              map.put("D", new Integer(antall.intValue()+1));            
                        } else if (K.equals("E")) {
                              map.put("E", new Integer(antall.intValue()+1));
                        } else if (K.equals("F")) {
                              map.put("F", new Integer(antall.intValue()+1));
                        } // end if                              
                        ImporterteVerdier[i] = K;
                        i++;
                  } // end while
            } catch (SQLException e) {} // end try/catch
      } // end method HentKarakter
} // end class HashMap_Oppg

--- End Code ---
*import hjelpefiler.KobleTilDb is a connection to an oracle database

The thing I want printed on screen is supposed to look something like this:
[E, B, A, F, D, C, E, E, F, B, D, F, A, B, C, D, D, B, F, D, A, A, C, F]
A 4
B 4
C 3
D 5
E 3
F 5

but what I get looks like this:
[null]

or

java.lang.ArrayIndexOutOfBoundsException: 1
      at HashMap_Oppg.HentKarakterer(HashMap_Oppg.java:78)
      at HashMap_Oppg.<init>(HashMap_Oppg.java:32)
      at HashMap_Oppg.main(HashMap_Oppg.java:45)
Exception in thread "main"

Any help appreciated.
eX.
0
Gaute Rønningen
Asked:
Gaute Rønningen
  • 11
  • 11
  • 11
  • +2
4 Solutions
 
girionisCommented:
> java.lang.ArrayIndexOutOfBoundsException: 1

This means that you are trying to access an element that is out of bounds (for exampel you have ten elements but you are trying to access the eleventh). Which line throws the error?

0
 
Gaute RønningenAuthor Commented:
The one in middle:

...                      
                    } // end if                        
                    ImporterteVerdier[i] = K;
                    i++;
...
0
 
zzynxSoftware engineerCommented:
What are you trying to do with this combination?

>> private static String ImporterteVerdier[] = {null};
and
>>List liste = new ArrayList(Arrays.asList(ImporterteVerdier));

?

0
Independent Software Vendors: 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!

 
Gaute RønningenAuthor Commented:
Secondly the:
          while (it.hasNext()) {
               System.out.println(it.next());
          } // end while
does not print anything...

0
 
objectsCommented:
>         ImporterteVerdier[i] = K;

ImporterteVerdier only has a single element

     private static String ImporterteVerdier[] = {null};
0
 
girionisCommented:
> he one in middle:

> ...                      
>                     } // end if                        
>                     ImporterteVerdier[i] = K;
>                     i++;

How big is importerteVerdier? What is the value of i at the moment of the exception? I guess it is bigger than the index of the last element of the ImporterteVerdier.
0
 
objectsCommented:
you need to make your array as big as the number of rows that could be returned in resulkt set
eg. if 100 is enough then:

     private static String ImporterteVerdier[] = new String[100];
0
 
zzynxSoftware engineerCommented:
with
>> private static String ImporterteVerdier[] = {null};

you only create memo space for
     ImporterteVerdier[0]

0
 
zzynxSoftware engineerCommented:
>> you need to make your array as big as the number of rows that could be returned in resulkt set
Voilà, that's it.
0
 
girionisCommented:
Do not use an array at all. Use a Vector or an ArrayList that can expand dynamically.
0
 
Gaute RønningenAuthor Commented:
What if I don't know the number of rows that could be returned?
0
 
girionisCommented:
> What if I don't know the number of rows that could be returned?

Use a Vector or an ArrayList that can expand dynamically.
0
 
Gaute RønningenAuthor Commented:
> Use a Vector or an ArrayList that can expand dynamically.

How to switch?
0
 
zzynxSoftware engineerCommented:
>> What if I don't know the number of rows that could be returned?

Replace
>> private static String ImporterteVerdier[] = {null};
by
private static List ImporterteVerdier = new ArrayList();

and
>>ImporterteVerdier[i] = K;
by
ImporterteVerdier.add( K );
0
 
girionisCommented:
Simply do this:

Vactor ImporterteVerdier = new Vector();
ImporterteVerdier.addElement(K);

and to read it back use:

String myString = (String) ImporterteVerdier.getElementAt(<index>);
0
 
Gaute RønningenAuthor Commented:
Third:
The output from hashmap is now:
D=5
A=4
F=5
C=3
B=4
E=3

How do I order them alphabetically?
0
 
zzynxSoftware engineerCommented:
... and of course

>>List liste = new ArrayList(Arrays.asList(ImporterteVerdier));
>>System.out.println(liste);

can be

System.out.println(ImporterteVerdier);


0
 
objectsCommented:
> How do I order them alphabetically?

Use a TreeMap instead of a HashMap.
0
 
zzynxSoftware engineerCommented:
>> How do I order them alphabetically?
By sorting it's Key set
0
 
girionisCommented:
> How do I order them alphabetically?

Use Collections.sort(ImporterteVerdier);
0
 
girionisCommented:
> > How do I order them alphabetically?

> Use Collections.sort(ImporterteVerdier);

I am assuming that ImporterteVerdier is an object of type Vector, ArrayList or any subtype of List. If it is an array it won't work.
0
 
Gaute RønningenAuthor Commented:
> Use Collections.sort(ImporterteVerdier);

Where? In the while loop?
0
 
zzynxSoftware engineerCommented:
>>Where? In the while loop?
Before printing it out
0
 
girionisCommented:
> > Use Collections.sort(ImporterteVerdier);

> Where? In the while loop?

After you have assigned all the elements in the ImporterteVerdier variable. After you finish the while loop and before accessing the elements.
0
 
zzynxSoftware engineerCommented:
> Use Collections.sort(ImporterteVerdier);
Wait a minute, I think you don't want the list to be sorted, but the (output of the) map...
0
 
Gaute RønningenAuthor Commented:
Yea, that's right...
0
 
girionisCommented:
Go with object's suggestion then.
0
 
petmagdyCommented:
u didn't initalize ImporterteVerdier[]  correctly, at the begeining of   private void HentKarakterer()
first ur member declaration should be like this:

 private static String[] ImporterteVerdier = null;

u should get the count of rows and initialize based on this count like this:

ImporterteVerdier = new String[urRowsCount];
0
 
objectsCommented:
then use a TreeMap instead of a HashMap as I suggested earlier.
0
 
zzynxSoftware engineerCommented:
Set set = map.keySet();
Collections.sort(set);
Iterator it = set.iterator();
while (it.hasNext()) {
   String key = (String)it.next();
   Integer int = (Integer)map.get(key);
   System.out.println(key + "=" + int);
}
0
 
Gaute RønningenAuthor Commented:
Feeling like I ask alot of questions...
Another; how to use TreeMap?
0
 
zzynxSoftware engineerCommented:
>> then use a TreeMap instead of a HashMap as I suggested earlier.
Indeed, or
>> by sorting it's Key set as in the my previous comment

0
 
girionisCommented:
> Feeling like I ask alot of questions...
> Another; how to use TreeMap?

Same way as you use hashMap :)
0
 
objectsCommented:
> how to use TreeMap?

just replace HashMap with TreeMap.
0
 
Gaute RønningenAuthor Commented:
Works. :-)

Now I think I'm gonna split some points...
0
 
zzynxSoftware engineerCommented:
Thanks for accepting
0
 
Gaute RønningenAuthor Commented:
Split as follows:
300 to zzynx
150 to objects
50 to girionis - for trying ;-)
0
 
girionisCommented:
:)
0
 
Gaute RønningenAuthor Commented:
28 new EE messages in inbox...
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 11
  • 11
  • 11
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now