Object array issue - java

I wan to know why am I getting a null pointer exception on the line marked below, I am trying to add stuff from a properties table to the object map, so I can insert column information into a JTable dont know if its 100% clear, but any input will be appreciated
public Object getList(){
dvd.loadList(dvd.dvdInventory);
Object [][] data = null;
int i = 0;
int j = 0;
Iterator<Object> kitr= dvd.dvdInventory.keySet().iterator();
Iterator<Object> itr = dvd.dvdInventory.values().iterator();
while(itr.hasNext()){
String key = (String) kitr.next();
String values = (String) itr.next();
String[] tokens = values.split(" / ");
for ( String token : tokens ){
data[j][i] = token.toString(); <------this line gets null
i++; pointer exception
}
i = 0;
j++;
}
return data;
}

Object [][] data = null;
The array is null. YOu need to allocate space:
Object [][] data = new Object[5][5];
or whatever size you want.
Unless you know the size of the row/columns of the array it is better to use a Vector of Vectors for the DefaultTableModel of JTable.
Edit:
To use Vectors you would restructure the code to be something like:
Vector<Vector<String>> data = new Vector<Vector<String>>();
while(itr.hasNext())
{
String key = (String) kitr.next();
String values = (String) itr.next();
String[] tokens = values.split(" / ");
Vector<String> row = new Vector<String>();
for ( String token : tokens ){
row.add(token.toString());
}
data.add(row);
}

Null pointer exception is happening because you have initialized your array as null. You need to allocate some memory to your array, right now it is just null as defined here:
Object [][] data = null;
You should know, what size do you need to for the array that you have. You cannot simply initialize it to any value. If you don't know the size then consider using the collections, which can grow dynamically.
You may consider using List of Arraylist and define it as :
List<List<Object>> lists = new ArrayList<List<Object>>();

Related

ArrayList<Objects[]> to strings to use in SQL IN statement

I am trying to build a string to pass it as an SQL query within the IN statement.
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
This still prints out the memory locations instead of the actual string
askldnlkasdn[[Ljava.lang.Object;#7bb11784, [Ljava.lang.Object;#33a10788, [Ljava.lang.Object;#7006c658, [Ljava.lang.Object;#34033bd0, [Ljava.lang.Object;#47fd17e3, [Ljava.lang.Object;#7cdbc5d3, [Ljava.lang.Object;#3aa9e816, [Ljava.lang.Object;#17d99928, [Ljava.lang.Object;#3834d63f, [Ljava.lang.Object;#1ae369b7]
I have also tried out
using StringBuilder and StringUtils. But things dont seem to work.
Any inputs as to where the problem is?
you should override method toString in your objects
You can use an SQL specific java Array.
try (PreparedStatement stmt = connection.prepareStatement("... IN (?) ...")) {
Object[] elements = ...
stmt.setArray(1, connection.createArray("TEXT", elements));
stmt.executeUpdate();
}
The problem you have is that you are implicitly using the toString() method of the Object elements inside your ArrayList. By default, that method returns the class and address of the Object. You should override the toString() method in every class you will use inside the list so it returns what you want it to.
This is new code that may help,
// Data of Array of Object for test the Code
Object[] a = new Object[1];
a[0] = "Hello";
Object[] b = new Object[1];
b[0] = "Friend";
Object[] c = new Object[1];
c[0] = "This is";
Object[] d = new Object[1];
d[0] = "Just Test";
// The Array List of objects and the data entry
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
// New List of strings
List<String> strings = new ArrayList<>(arrayList .size());
// The Process of adding the data from array list of objects to the strings
for(int i = 0; i < arrayList.size(); i++){
strings.add((String) arrayList.get(i)[0]);
}
// Just for print the data to console
for(int i = 0 ; i < strings.size(); i++){
System.out.println(strings.get(i));
}
System.out.println("askldnlkasdn "+strings.get(0));
I hope that solve the problem, if not please inform me, you can use it for more than one dimensional array.
You can just save it as String , like this code
ArrayList<String> arrayList = new ArrayList<>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
Or you want it Object for specific purpose?

Swings: storing the selected values from List into an array.

I made a List in java as under:
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList places = new JList(names) ;
Then in order to access the selected values I wrote in valueChanged method :
String[] emailID= places.getSelectedValuesList().toString[];
which is coming out to be incorrect ... Kindly help how should I rewrite this line so as the selected values get stored in array.
If you want to have all selected Items as an Array you can do something like this:
public static void main(String[] args){
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList<String> places = new JList<String>(names) ;
places.setSelectedIndices(new int[]{0,1,2});
String[] emailIDs = places.getSelectedValuesList().toArray(new String[]{});
for(String s : emailIDs){
System.out.println(s);
}
}
Note:
I added <String> to the List, because I assume you always want to have Strings as values. That way you can get the List .toArray() method with a generic output. Else you'd need to get an Object[] (Object Array) and cast the values.
For Storing Selected Items in String Array you can try this
Object[] values = places.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}

Accessing multi dimensional ArrayList values

I am getting 3 columns for each row from mysql table by using ResultSet. I am not sure about the number of rows I will get by using query. To store those rows I am using ArrayList as given code below:
while (rs.next())
{
String[] row = new String[numcols];
for (int i = 0; i < numcols; i++)
{
row[i] = rs.getString(i + 1);
}
rowsList.add(row);
}
rs.close();
When I debugged the code I found columns values are present in the ArrayList. Now I am unable to access the columns values because rowsList.get(index) will return only value at specific index but I have further 3 more values at that index how to access those values.
List.get() in your case will return a String array: String[]. You can access the elements of an array by using the [] index operators:
String[] row = rowList.get(0);
for (int i = 0; i < row.length; i++)
System.out.println(row[i]);
// Or you can use the enhanced for to loop through the array:
for (String s : row)
System.out.println(s);
If you want to process all rows:
for (String[] row : rowList) {
// Process row
for (String s : row) {
// Do something with the string
}
}
I would like to suggest you to learn about List.
And the second would be to create a class that holds everything that comes from your query.
And finally save each object of the class to the array.
Example
Suppose you get id, name and address columns from your query
Create a class
public class YourClass{
int id;
String name, address;
//create getters and setters or use a constructor
//example of setter to set field id
public void setId(int id){
this.id = id;
}
}
And then while retrieving the records from query, create an object of your class and set the columns as field of your class as follow:
YourClass anObject = new YourClass();
anObject.setId(id);// get similar columns from query
anObject.setName(name);
And finally add the object to the ArrayList as below:
yourArrayList.add(anObject);
To take care of multiple number of records you need to keep these code inside the while loop
And define your List before while loop as follow:
List<YourClass> yourArrayList = new ArrayList<YourClass>();
And I think this is the best approach as it uses OOP that you should begin using instead of using bare array.
you would want to specify what object is in the list. to achieve this make your List to List<String[]> rowsList = new ArrayList<String[]>();
then use your while loop
while (rs.next())
{
String[] row = new String[numcols];
for (int i = 0; i < numcols; i++)
{
row[i] = rs.getString(i + 1);
}
rowsList.add(row);
}
rs.close();
when you access each item in the list it will always return a String[] which you can iterate to get the values.
for(int i = 0 ; i< rowsList.size() ; i++){
rowsList.get(i);//will return a String[]
}
OR
for(String[] rows : rowsList){
//iterate the rows
}

null pointer exception string 2d array in java

public String[][] fetchData()
{
String[][] data = null;
int counter = 0;
while (counter < 10){
data[counter] = new String[] {"abc"};
counter++;
}
return data;
}
Getting the error in this loop.
Please let me know where i am wrong
You need to allocate memory to data.
String[][] data = new String[ROW][COLUMN].
Read this
String[][] data = null;
==> you have a null pointer exception when you try to write in data
You might do
String[][] data = new String[10][];
You get a NPE because you explicitly set data to null:
String[][] data = null;
You need to allocate the number of rows first:
String[][] data = new String[][NUMBER_OF_ROWS];
data[counter] = new String[] {"abc"};
Here you are putting "abc" to array, but why you're using array if it has only one cell?
data[counter] = new String("sample string");
would be enough. And ofc you need also to declare "data" as one-dimensional array.

Sorting a list of maps within before this while loop runs out(Java)

A database call is made and result is a bunch of rows of two string columns of type A and B. e.g. (x_a, y_b), (x_a, y1_b), (x2_a,y_b)
The idea is to come up with a list of maps like {(x_a,{y_b,y1_b}), (x2_a,{y_b})} where the objects of type A are not repeated and to do this while pulling the results from a database.
Here's what I tried:
int i =0;
List<String> type2 = new ArrayList<String>();
Map<String,List<String>> type1_type2 = new HashMap<String,List<String>>();
List<Map> list_type1_type2 = new ArrayList<Map>();
String [] type1Array = new String[100];
String [] type2Array = new String[100];
int trackStart = 0;
while (res.next()){
String type1 = res.getString(1);
String type2 = res.getString(2);
type1Array[i]=type1;
type2Array[i] = type2;
if(i>0 && !type1Array[i].equals(type2Array[i-1])){
int trackStop = i;
for(int j = trackStart; j<trackStop;j++){
type2.add(type2Array[j]);
}
type1_type2.put(type1Array[i-1], type2);
list_type1_type2.add(type1_type2);
//debugging stuff
String x = list_type1_type2.toString();
System.out.println(x);
System.out.println(" printing because "+ type1Array[i]+" is not equal to " + type1Array[i-1]);
type2 = new ArrayList<String>();
type1_type2 = new HashMap<String,List<String>>();
trackStart=i;
}
i++;
}
This method does not work when the last type1 values of the result object are the same.
Is there a way to do this in the same spirit (within the while(res.next)) without first storing the results of the database call in separate arrays or adding an extra for loop outside the while loop to "patch it up"?
The simple way to do this is to use a Guava / Google Collections SetMultiMap. This is essentially a mapping from a key (your 'A' objects) to a set of values (your 'B' objects).
[I'm not going to try to code it for you. Your current code is too horrible to read ... unless you were paying me :-) ]
However, a better idea would be to get the database to do the collation. If you can do that, you will reduce the amount of (redundant) data that gets send across the database connection ... assuming that you are using JDBC.
If you don't want duplicates like {x_a:[y_b, y_b]} then use a set as the value of your map:
Map<String,Set<String>> type1_type2;
I don't know what the other various list and arrays are for. You can probably just get by with the type1_type2 map. Process each (x, y) in pseudo-code:
Set s = type1_type2.get(x)
if s == null:
s = new Set()
type1_type2.put(x, s)
s.add(y)

Categories

Resources