ArrayList Cast in java Combo box - java

Hi there i have this code
public void comboCountry(List<Countries> cs) {
country = db.fillComboCountries();
DefaultComboBoxModel dcbm = (DefaultComboBoxModel) CountryComboBox.getModel();
for (int i = 0; i < country.size(); i++) {
String row[] = new String[country.size()];
//row[i] = String.valueOf(country.get(i).getCountryId());
row[i] = country.get(i).getCountryName();
// row[i] = country.get(i).getCountryCode();
dcbm.addElement(row);
}
}
with country = db.fillComboCountries(); i query the database and load everything into an ArrayList.
The Arraylist is country.
When i load my data into combobox i get
[Ljava.lang.String;#fdfc58
how can i avoid that and get the value that i want?
I have try with Arrays.tostring(), but i get also [ ].

Instead of dcbm.addElement(row); use dcbm.addElement(country.get(i).getCountryName());
With this, you will add individual elements of an array rather than array itself. Also you would avoid creating arrays with every item in the country list.

You are creating a new String array in each iteration, you should initialize the array before the for loop:
String row[] = new String[country.size()];
for (int i = 0; i < country.size(); i++) {
...
}
If you only want to add the countryName in each iteration, you don't need the array at all:
for (int i = 0; i < country.size(); i++) {
String countryName = country.get(i).getCountryName();
dcbm.addElement(countryName);
}
Or:
for (Country c : country) {
dcbm.addElement(c.getCountryName());
}

Related

How to properly add data from String[] to ArrayList<String[]>

so for my school project we will be working with an SQL database and have to show the values on a JFrame panel.
For data to show in a JTable we have to require next syntaxt: (def)
JTable table = new JTable(String[][] data , String[] header);
Since I don't know how many queries I will have to handle we will read them into a ArrayList<String[]> . Every time I press the button this method parseJSON will be called and I will create a new 2D-ArrayList consisting of String arrays aka String[] elements
public class DBTest {
public ArrayList<String[]> dataArr = new ArrayList<>();
public String[] varArr = new String[3];
public ArrayList<String[]> parseJSON(String jsonString){
try {
JSONArray array = new JSONArray(jsonString);
dataArr = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
varArr[0] = curObject.getString("nameSensor");
varArr[1] = curObject.getString("value");
varArr[2] = curObject.getString("unitSensor");
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
for (int i = 0; i < array.length(); i++) {
System.out.println(dataArr.get(i));
}
return dataArr;
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
For the first print: I will get the proper Values e.g.
Output
["Weight","500","g"]
["Height", "3", "m"]
But once I add these String[] arrays to the ArrayList and print it I will get:
Output
["Height", "3", "m"]
["Height", "3", "m"]
I want to add one point to #LuiggiMendoza's answer....
In Java, arrays are basically Objects. The reason why creating a new array in each iteration (local to the method) is because the original code was literally overwriting the value of a single object and placing said reference to three different index location on the ArrayList rather than creating distinct references. Therefore, the last System.out.print() was printing out the same array element value for each iteration of the list. In fact, even if the array was created outside the loop, the result would've been the same as the original code. EACH ITERATION needs a new array for this to work.
Move String[] varArr as a local variable in your method:
public class DBTest {
public ArrayList<String[]> dataArr = new ArrayList<>();
//Remove this line of code (delete it)
//public String[] varArr = new String[3];
public ArrayList<String[]> parseJSON(String jsonString){
try {
JSONArray array = new JSONArray(jsonString);
dataArr = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
//declare it locally
String[] varArr = new String[] {
curObject.getString("nameSensor"),
curObject.getString("value"),
curObject.getString("unitSensor")
};
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
for (int i = 0; i < array.length(); i++) {
System.out.println(dataArr.get(i));
}
return dataArr;
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
Other improvements:
Try to design your code to work with interfaces rather than concrete classes e.g. return List instead of ArrayList
Avoid returning null in case the method failed. It'd be better if you return an empty list or throwing a custom exception with a proper message that helps you understand the issue. This also leverages your maintenance effort.
Use attributes only if you need to maintain the state (the values) for later use. Otherwise, it'd be better to use local variables instead. dataArr attribute seems to not be needed (at least from this piece of code).
Wrapping everything, this is how the code would look:
public class DBTest {
public List<String[]> parseJSON(String jsonString) {
List<String[]> dataArr = new ArrayList<>();
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
String[] varArr = new String[] {
curObject.getString("nameSensor"),
curObject.getString("value"),
curObject.getString("unitSensor")
};
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
for (int i = 0; i < array.length(); i++) {
System.out.println(dataArr.get(i));
}
}
catch (JSONException e) {
e.printStackTrace();
}
return dataArr;
}
}
The issue lies in the following block of code.
public String[] varArr = new String[3];
...
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
varArr[0] = curObject.getString("nameSensor");
varArr[1] = curObject.getString("value");
varArr[2] = curObject.getString("unitSensor");
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
At each iteration of the for-loop, you are doing the following:
Mutate (set values into) the same array instance, which you had instantiated and assigned to the variable varArr before the for-loop.
Add a reference of this array instance to the ArrayList dataArr.
The outcome is that you have added references of the same array instance to the ArrayList multiple times.
Since you were just updating the same underlying array instance over and over again, hence what you get at the second print statement is the last-updated value of that same array instance, printed multiple times.
To fix this, simply move the varArr declaration statement into the for-loop as below. What this does is that at each iteration of the for-loop, a new array instance is created and added to the ArrayList instead.
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
String[] varArr = new String[3]; // move this here
varArr[0] = curObject.getString("nameSensor");
varArr[1] = curObject.getString("value");
varArr[2] = curObject.getString("unitSensor");
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}

converting from Object to string in java

I have this below method
public List<Object> ProductbyJobcode (String jobcode)
{
List<Object> temp = new ArrayList<Object>();
temp = riskJobCodeProductMappingDAO.fetchProductByJobCode(jobcode);
return temp;
}
and i am taking the input in the Object list from the above method into Object type of list
List<Object> temp = new ArrayList<Object>() ;
temp = ProductbyJobcode(jobcode);
now i am trying to retrieve the value into string but i am getting exception, please advise how to achieve the same how i will convert the object to string
String Product ;
String Actiontype;
for (int i = 0; i < temp.size(); i++) {
product = temp.get(0).toString();
Actiontype = temp.get(1).toString();
}
Object.toString() could provide NPE. So more suitable method is String.valueOf().
String Product = temp.size() >= 1 ? String.valueOf(temp.get(0)) : null;
String Actiontype = temp.size() >= 2 ? String.valueOf(temp.get(1)) : null;
Well this
for (int i = 0; i < temp.size(); i++) {
product = temp.get(0).toString();
Actiontype = temp.get(1).toString();
}
doesn't really test the bounds of the list correctly; you might only have one String in the list, which will mean temp.get(1) throws an IndexOutOfBoundsException.
It's not clear what exactly you're trying to achive, but this should work:
for (int i = 0; < temp.size; i++) {
System.out.println(temp.get(0));
}
If you really need the two items, you probably want something like this
product = (temp.isEmpty()) ? null : temp.get(0).toString();
actionType = (temp.size() > 1) ? temp.get(1).toString() : null;
The problem is that if your temp list contains only 1 element you try to get second element in this line:
Actiontype = temp.get(1).toString();
That cause:
java.lang.IndexOutOfBoundsException
Because you try to get second element when the list contains only one

Break ArrayList into ArrayList of ArrayLists dynamically

I am trying to make a method to breakdown an arrayList of objects into multiple arrayLists based on an attribute value of the myObj class.
private static ArrayList<ArrayList<Ticket>> splitList(ArrayList<Ticket> arrayList){
ArrayList<ArrayList<Ticket>> smallLists = new ArrayList<>();
for(int i = 0; i < arrayList.size(); i++){
for(Ticket eachTick: Ticket.getTickets()){
if(arrayList.get(i).getCategory().equals(eachTick.getCategory())){
smallLists.add(...);
}
}
}
return smallLists;
}
If there is a better way to do what I am attempting, please advise me.
Are you trying to create a list for each ticket category found in the input list? If that's the case, then I agree with Dawood ibn Kareem: use a map that looks up the proper list based on the category. Something like this:
private static ArrayList<ArrayList<Ticket>> splitList(ArrayList<Ticket> inputList) {
Map<String, ArrayList<Ticket>> map = new HashMap<>();
// your ticket categories here
// (array used for simplicity; you should use a Set, and you should also maintain the valid categories inside your Ticket class, not here)
String[] categories = new String[] {'a', 'b', 'c' };
for (int i = 0; i < categories.length; i++) {
map.put(categories[i], new ArrayList<Ticket>());
}
for (int i = 0; i < inputList.size(); i++) {
Ticket t = inputList.get(i);
map.get(t.getCategory()).add(t);
}
// Convert to list of lists
return new ArrayList<>(map.values());
}

Converting List<ArrayList> to String[]

I have a
List<ArrayList> arg = new ArrayList<ArrayList>();
with
[[logo], [cd_branche], [lib_branche]],
(other arguments not relevant)
[[1111,22222,3333]],[[2222,324,432]]...
and I want to cast it to a String[] so I did this
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= (String) obj[i];
}
but I'm getting
java.util.ArrayList cannot be cast to java.lang.String
The output I'm looking for is
headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche
Using Java 6
It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").
In that case simply do:
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= Arrays.toString(obj);
}
And each one of your ArrayList objects inside obj will be returned in string array format.
UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:
int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());
String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
for (int j=0; j< arg.get(i).size(); j++) {
headers[count++]= arg.get(i).get(j).toString();
}
}
String headers = "";
for (String header:arg)
{headers += header;}

Java nested conditional parsing of CSV file

If my sample data is a CSV file that looks like this:
a,,,b,
36,28,90,5,24
what would be the best way to either have something like
myStringArray = [a, [36,28,90]], [b, [5,24]]
or
myStringArray1 = {a,b}; // this part i can do
myStringArray2 = {{36,28,90}, {5,24}};
I am using Processing, which is based on Java, but my question is more about the general functionality of Java, so excuse my code formatting, if it doesn't appear java correct.
here is my import class:
class dTable {
int rowCount;
int columnCount;
String[][] data;
String filename;
dTable(String _filename) {
filename = _filename;
}
void load() {
String[] rows = loadStrings(filename);
String[] columns = split(rows[0], ',');
rowCount = rows.length;
columnCount = columns.length;
//set the size of the matrix
data = new String[rows.length][columns.length];
// add column pieces into data matrix
for (int i = 0; i < rows.length; i++) {
String[] colEntries = split(rows[i], ',');
for (int j = 0; j < columns.length; j++) {
data[i][j] = colEntries[j];
}
}
}
}
and here is my unworking attempts at a parsing class:
class dParse {
String[] bMaj;
String[][] bMin;
dParse() {
}
void getList(int integer) {
ArrayList dMaj = new ArrayList();
ArrayList dMin = new ArrayList();
String[][] minimums;
String[] _rowNameMaj = table.data[0]; //get data first to match
String[] _rowName = table.data[integer]; // get data to fill
//get first variables
for (int i = 0; i<_rowName.length; i++) { //iterate over
ArrayList tempMin = new ArrayList();
if (trim(_rowNameMaj[i]).length() != 0) {
dMaj.add(_rowNameMaj[i]);
}
}
//place maj values from arraylist into an array
String[] _bMaj = (String[]) dMaj.toArray(new String[0]);
bMaj = _bMaj; //set value to global variable
//min values
ArrayList bigOne = new ArrayList();
int count = 0;
for (int i = 0; i<_rowName.length; i++) { //iterate over
ArrayList tempMin = new ArrayList();
if (trim(_rowNameMaj[i]).length() != 0) { //check if box is not empty & set count to 0
//tempMin = dMaj.get(i); // set inner list
//println("maj " + count + " " + _rowNameMaj[i]);
tempMin.add(_rowName[i]);
count++;
//println("min" + count + " " + tempMin);
}
else if (trim(_rowNameMaj[i]).length() == 0) { //if next box is empty, add to count
count++;
tempMin.add(_rowName[i]);
//println("min" + count + " ");
}
minimums = new String[_bMaj.length][];
/various unworking attempts below
//place min values from arraylist into an array
//String[] temp_bMin = (String[]) tempMin.toArray(new String[0]);
//fl[] = append((new String(temp_bMin)), fl);
for (int n = 0; n< bMaj.lenth; n++ ) {
count[level]mums[n] = (String[]) toArray(new String[0]);
// println(minimums[n]);
// }
tempMin.clear(); //clear temporaryList
}
}
String[] getMaj() {
return bMaj;
}
String[][] getMin() {
return bMin;
}
}
Any help is appreciated,
Many thanks,
Dimitar
Dimitar... Perhaps a library such as Commons CSV or the links to the other libraries on that page would prove useful? However, if you insist on rolling your own CSV parser, look into the java.util.StringTokenizer class.
Pseudo code:
class Item {
String name;
List<String> values;
}
String[] names = line1.split(",");
String[] data = line2.split(",");
List<Item> items = new ArrayList<Item>();
Item curItem = null;
for (int i=0; i<data.length, i++)
{
if (names[i].isEmpty())
{
if (curItem == null) throw "first name is empty";
}
else
{
curItem = new Item();
items.add(curItem);
}
curItem.values.add(data[i]);
}
This uses an Item class to hold each item and a List<Item> for the whole thing. Downgrading to use nested arrays is left as an exercise.
Important If you need real CSV parsing (quoted fields, etc) you should use a CSV library to do the initial split and then apply the logic above to the results.

Categories