I am trying to make some DataBase class. I know that I want each column to be represented as ArrayList.
I want to create Constructor as that
DataBase(String[] columnNames, String[] types)
so for example
DataBase({"Column1","Column2","Column3"},{"int","string","myOwnType"})
I tried to make it with HashMap which will have column name as key and ArrayList as value.
This is what I got so far.
public class DataFrame {
public HashMap<String, ArrayList> data;
public String[] names;
public String[] types;
public DataFrame(String[] names, String[] types) {
data = new HashMap<String, ArrayList>();
nazwy = new String[_names.length];
typy = new String[_types.length];
for(int i = 0; i < _names.length; i++) {
ArrayList column = new ArrayList<>();
data.put(_nazwy[i], column);
}
}
}
How can I create a column of type given in program? I thought about creating ArrayList and then make Map which will have label and that list, but I cant find how to do that.
In your method, this Loop is re initializing the arraylist so it is not possible to store the records.
for(int i = 0; i < _names.length; i++) {
ArrayList column = new ArrayList<>();
data.put(_nazwy[i], column);
}
Always good to have List. Map will represent each records with column names so that it will easy for processing.
ArrayList list = new ArrayList(50);
HashMap row = new HashMap(columns);
for(int i=1; i<=columns; ++i){
row.put(getColumnName(i),data(i));
}
list.add(row);
Related
I want to use a data structure to store column names of a JTable with their respective indexes, so that I can select the corresponding data column. If I filter out a column name, then the name and the index gets removed, if I put it back, the index will be the same. If I want to swap two columns, the indexes change but the column names stay the same. It also has to be serializable. Can I do this with a HashMap<String,Integer>?
I managed to load it with values, I basically filtered the dataList with the selected columnNames. I'm not too familiar with maps. As far as a know, I can't "swap" key's in HashMap
private List<Object[]> data = new ArrayList<Object[]>();
private List<String> columnNames = new ArrayList<String>();
public CustomTableModel(List<Object[]> dataList, Map<Integer,String> columnNames) {
for (Map.Entry<Integer, String> set : columnNames.entrySet()) {
this.columnNames.add(set.getValue());
}
ArrayList<Integer> selectedColIndexes = new ArrayList<Integer>();
for (Map.Entry<Integer, String> set : columnNames.entrySet()) {
selectedColIndexes.add(set.getKey());
}
for(int n=0; n<dataList.size(); n++) {
Object[] selectedRow = new Object[columnNames.size()];
for(int j=0; j<selectedColIndexes.size(); j++) {
int index = selectedColIndexes.get(j);
selectedRow[j]=dataList.get(n)[index];
}
data.add(selectedRow);
}
}
I am trying to create an array of objects with a MAX_N 6 object into this array, then create another array within an else statement to fit the rest of the array objects.
I would like to name the new array
sbag1
sbag2
etc
here is my code:
public static ShoppingBag[] packIntoBags(GroceryItem[] goods) {
ShoppingBag newBag = new ShoppingBag();
GroceryItem tmpObject = null;
int index = 0;
String bag = "newBag";
String bagNum = bag + index;
for (int i = 0; i < MAXNBAG; i++)
if (newBag.numItems() < MAX_NUM_ITEMS) {
for (int k = 0; i < MAX_NUM_ITEMS; i++) {
tmpObject = goods[i];
newBag.addToBag(tmpObject);
}
}
else {
ShoppingBag newBag1 = new ShoppingBag();
}
}
You will not be able to dynamically create new variables in java.
When I look at the signature of your method you don't need to return multiple variables, only an array of ShoppingBags.
You should create a variable of type List<ShoppingBag>:
List<ShoppingBag> shoppingsBags=new ArrayList<>();
each time you need a new ShoppingBag:
bag=new ShoppingBag();
shoppingBags.add(bag);
at the end convert this list to an array:
return shoppingBags.toArray(new ShoppingBag[0]);
Java is a statically compiled language. In general, it is not possible, or to be precise: not helpful to use "dynamic" names for variables.
What you could do instead: use a Map, or even more simple: an array of arrays to hold your data.
I have two patterns of lists inside a big list.
[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]
To put in simple words, it is a combination of
[ [pricesList1], [DurationList1], [PricesList2], [DurationList2],... ]
I now want to create a new list with the price and corresponding duration from both lists as a pair from each set. For Example :
[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]
I have tried using List<List<Object>> and List<List<String>>. But no use. How can I do this?
I programed as following, which is wrong :
List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList = new ArrayList<List<String>>();
SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
}
}
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
}
}
Assuming the input list always has an even number of sublists and pairs of sublists have the same size, you can use a for loop iterating over the outer lists's element two by two :
List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
List<String> priceList = outerList.get(i);
List<String> durationsList = outerList.get(i+1);
for (int j=0; j<priceList.size(); j++) {
List<String> newEntry = new ArrayList<>();
newEntry.add(priceList.get(j));
newEntry.add(durationsList.get(j));
result.add(newEntry);
}
}
As commented I suggest defining your own class to store the price and duration rather than using that List<String> newEntry.
I have this constructor in another class
public <T> initializingWorkbook( Sheet sheet,List <T> column, int index)
{
int rows = sheet.getRows();
for(int row = 1;row < rows;row++)
{
String i = sheet.getCell(index, row).getContents();
coloana.add(Double.parseDouble(i)) ;
}
}
In the main() function I have to initialize all those Arrays at once. So when I call the initializingWorkbook() function I want all these arrays to be filled with data (I'm taking that data from an excel file).
ArrayList <Long> timeColumn = new ArrayList<>();
ArrayList <Double> pc1Column = new ArrayList<>();
ArrayList <Double> pc2Column = new ArrayList<>();
ArrayList <Double> ph1Column = new ArrayList<>();
ArrayList <Double> ph2Column = new ArrayList<>();
ArrayList <Double> ph3Column= new ArrayList<>();
Edit: I added what this constructor contains. So basically
-Sheet sheet is the sheet from where I read data;
-List <T> column is the variable where I stock the column;
-index is the number of the column.
I need to load all data in my ArrayList variables at once.
Thanks for your answers.
I think you are trying to represent a table, aren't you?
You could create a class for one record in the table, and store an ArrayList of this class.
public class MyClass {
public Long timeColumn;
public Double pc1Column;
public Double pc2Column;
public Double ph1Column;
public Double ph2Column;
public Double ph3Column;
}
You create the ArrayList like this:
ArrayList<MyClass> myTable = new ArrayList<>();
You add an element like this:
for(every row in the table) {
String cell1 = sheet.getCell(0, row).getContents();
String cell2 = sheet.getCell(1, row).getContents();
String cell3 = sheet.getCell(2, row).getContents();
String cell4 = sheet.getCell(3, row).getContents();
String cell5 = sheet.getCell(4, row).getContents();
String cell6 = sheet.getCell(5, row).getContents();
MyClass record = new MyClass();
record.timeColumn = Long.parseLong(cell1);
record.pc1Column = Double.parseDouble(cell2);
record.pc2Column = Double.parseDouble(cell3);
record.ph1Column = Double.parseDouble(cell4);
record.ph2Column = Double.parseDouble(cell5);
record.ph3Column = Double.parseDouble(cell6);
myTable.add(record);
}
The simplest solution would be a List of lists, then access them by index. Another option would be to put them in a Map. The choice would be dependent on how you plan to load the data and use it later.
Note, there is no need to use a concrete type, the generic one would be enough and it is also preferred.
List<Object> listOfObj = new ArrayList<>();
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
}