I'm trying to fill an Object[][] array with data from my Object Class. However im having problems filling the array. Below is what I am trying to do to fill the Object[][] data. at the moment the returned data variable cannot be seen by the method. I have tried removing the method and filling the array where rows in declared but cannot because there is a for loop.
Am I currently filling the object[][] array correctly?
public class CustomersDialog extends javax.swing.JDialog {
private CustomerList customers = new CustomerList();
Object rows[][] = getData();
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer = new Customer();
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
Object [][] data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
}
Further doing this method of creating the array outside the loop causes an 'empty statement message' by the compiler and it says it 'requires line ends ; after the .get statements':
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer;
Object [][] data;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
You're not doing it properly.
In your code, you're declaring an array INSIDE for loop, which means that after the loop, the array doesn't exist anymore. That's why you can't return data - it simply does not exist.
More about scope and lifetime of variables you can read there: http://www.c4learn.com/javaprogramming/the-scope-and-lifetime-of-variables-in-java-programming-language/
What you want to do is to declare array outside the loop:
Object [][] data;
for(int i; i < size; i++) {
// Filling data array
}
return data;
Next thing is that if you want to use an array, you should initialize it first:
Object [][] data = new Object [size][3];
Then you can fill it in for loop, like this:
for(int i; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i][0] = Integer.toString(customer.getCustomerID());
data[i][1] = customer.getfName();
data[i][2] = customer.getlName();
}
You have to allocate the array in two times. Once for the rows, and after once per row.
Object[][] data = new Object[size];
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i] =
new Object[]{
Integer.toString(customer.getCustomerID()),
customer.getfName(),
customer.getlName()
};
}
If you really want to use a 2 dimensional Array than you must define the size of the Array first (also if it is a n dimensional Array!)
See this content to get some clarification:
http://www.leepoint.net/notes-java/data/arrays/arrays-2D.html
It seems to me like you only have one size Parameter for the Array, so I would use a normal Array instead of a 2 dimensional one.
I would do something like this:
public Object[] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Object[] result = new Object[size];
Customer customer;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
result[i] = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
If you have to use a 2 dimensional Object Array, than you have to define the second size dimension and fill the array like this:
for(int i = 0; i < sizeDimOne; i++) {
for(int k = 0; k < sizeDimTwo; k++) {
result[i][k] = { { Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
}
Hope this is helpful.
Related
I am relatively new to java, and this is only the second time I have ever tried to design a program that has an array of class objects. I am having trouble because when I go into debug mode, it is showing me that the arrays are being built correctly. However, when I try to build a string or even print to the console, I am getting a null pointer exception.
I am trying to make an array of Slot class objects.
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
Slot[] s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
And the Slot class has its own array, block[], constructed by a value passed in through its constructor.
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
short block[] = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Later in the program I then try to print to the console or build a string and it always breaks when I try to use any element in the slot[] in the C class.
Have I instantiated and initialized my 2 different arrays correctly?
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
Try something like these instead
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Replace
short block[] = new short[byteSize];
with
block = new short[byteSize];
Always use a this operator to initialize in a constructor so that you may differentiate clearly between local variables and instance variables
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
this.block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
This is my homework(assignment). I really hope someone can help me figure out what I did wrong.
When I tried to create an object of State
state = new State(tablesize, tb);
and then tried to make a copy
State st2 = new State(state);
and then tried to modify the data in state
state.placeNumber(1,1,3);
for some reason, the data in st2 is also changed.
Below is the code. I really hope someone can point out where my mistake is.
Thanks
public class State
{
private int arraysize;
private int lastfilledx;
private int lastfilledy;
private int table[][];
//constructor
public State()
{
}
public State(State s)
{
arraysize = s.getsize();
lastfilledx = s.lastindex_x();
lastfilledy = s.lastindex_y();
table = s.gettable();
}
public State(int size, int[][] tb)
{
arraysize = size;
table = new int[size][size];
//copy the initial table which is a 2d array
table = tb;
for (int i = 0 ; i < size; i++)
{
for(int j = 0 ; j < size ; j++)
{
if ( table[i][j] == 1)
{
lastfilledx = i;
lastfilledy =j;
break;
}
}
}
}
public void placeNumber(int i, int j, int nextvalue)
{
lastfilledx = i;
lastfilledy = j;
table[i][j] = nextvalue;
}
public void printoutput()
{
for (int i=0; i < arraysize; i++)
{
for (int j=0; j < arraysize; j++)
System.out.print(" " + table[i][j]);
System.out.println("");
}
System.out.println("last fill " + lastfilledx + " " + lastfilledy);
}
public int[][] gettable()
{
return table;
}
public int getsize()
{
return arraysize;
}
public int lastindex_x()
{
return lastfilledx;
}
public int lastindex_y()
{
return lastfilledy;
}
}
public class Dikuho extends State
{
private static State state;
public static void main(String[] args) {
int tablesize = 3;
int tb[][] = new int[tablesize][tablesize];
/*****HARDCODE the table data***/
for (int i=0; i < tablesize; i++)
for (int j=0; j < tablesize; j++)
tb[i][j] = 0;
//test case for 3x3
tb[2][2] = 1;
tb[0][0] = tablesize*tablesize;
tb[0][1] = 7;
tb[1][0] = 8;
tb[2][1] = 2;
//initialize the state
state = new State(tablesize, tb);
**//Here is where the problem is. I only change the data in state but the data in st2 is also changed. I'm not sure what happen here.**
State st2 = new State(state);
state.placeNumber(1,1,3);
st2.printoutput(); **//These both printout same output which is not correct**
state.printoutput();
}
}
Your copy constructor has made a shallow copy of table 2D array. Both the original object and the copy refer to the same original array, because you assign the array reference from the original to the new object. That's fine for the int values, because the values are copied. But that's not okay for objects, for which references to the obejct are copied.
Instead of just copying the reference to the array...
table = s.gettable();
You'll need to create a new, copied array:
table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents
public int[][] gettable()
{
return table;
}
So, both of your state objects are referencing the same array. you need to create a new array for each instance.
The code block is listed below:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
This is the Vertex class:
public class Vertex implements Comparable<Vertex> {
public int arcWeight;
public int preDelay;
public boolean infinite = true;
public int nodeDelay = 0;
public Vertex predecessor = null;
public ArcNode firstArc = null;
public int mark = 0;
public int starTime;
public int finishTime;
public ArrayList<ArcNode> inArcList = new ArrayList<ArcNode>();
public ArrayList<ArcNode> outArcList = new ArrayList<ArcNode>();
}
Actually, I just want to copy the element in AdjList to a new array subgraph. But the error message shows that "java.lang.NullPointerException" and shows the problem lies in "subGraph[i].nodeDelay = AdjList[i].nodeDelay;" line.
I tested by printing to the console. And found the AdjList.length is 8 and the problem occurs in the very first round; And even when I only write "subGraph[i].nodeDelay;" without assigning any value to it, it also shows the wrong message.
Any idea on this? Thanks in advance.
Add it inside the loop:
subGraph[i] = new Vertex();
You first need to instantiate an object (subGraph[i] in your case) before accessing it.
The answer is: uninitialized variable. You did initialize subGraph to be an array, but you did not initialize subGraph[i].
When you create an object array in java, it's automatically initialized with null values. It's your responsibility to loop on the array an populate it with references to new objects.
In your case, you should assign Vertex objects to all array positions.
You need to create a Vertex instance and place it in the array prior to setting any fields.
Something like:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
subGraph[i] = new Vertex(); // adding instance prior to setting fields.
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
On add
subGraph[i] = new Vertex();
before this line
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
Because subGraph[i] is initially null . So subGraph[i].nodeDelay will obviously throw a NullPointerException, because you are trying to access or modify the field of a null object. Array of references will always be initialized with elements of null references by default.
In Java how do you convert a ArrayList into a two dimensional array Object[][]?
From comments: I will describe you the problem with more details: an XML file includes a list of contacts (e.g. name, address...). The only way I can obtain this information is through an ArrayList, which will be given to me. As I need to store the content of this array list in a Java Swing table in an ordered manner, I was thinking to convert it into a two dimensional array of objects
I presume you are using the JTable(Object[][], Object[]) constructor.
Instead of converting an ArrayList<Contact> into an Object[][], try using the JTable(TableModel) constructor. You can write a custom class that implements the TableModel interface. Sun has already provided the AbstractTableModel class for you to extend to make your life a little easier.
public class ContactTableModel extends AbstractTableModel {
private List<Contact> contacts;
public ContactTableModel(List<Contact> contacts) {
this.contacts = contacts;
}
public int getColumnCount() {
// return however many columns you want
}
public int getRowCount() {
return contacts.size();
}
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0: return "Name";
case 1: return "Age";
case 2: return "Telephone";
// ...
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
Contact contact = contacts.get(rowIndex);
switch (columnIndex) {
case 0: return contact.getName();
case 1: return contact.getAge();
case 2: return contact.getTelephone();
// ...
}
}
}
Later on...
List<Contact> contacts = ...;
TableModel tableModel = new ContactTableModel(contacts);
JTable table = new JTable(tableModel);
The simple way is to add a method to the Contact like this:
public Object[] toObjectArray() {
return new Object[] { getName(), getAddress, /* ... */ };
}
and use it like this:
ArrayList<Contact> contacts = /* ... */
Object[][] table = new Object[contacts.size()][];
for (int i = 0; i < contacts.size(); i++) {
table[i] = contacts.get(i).toObjectArray();
}
Try this:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
int[][] a = new int[list.size()][list.size()];
for(int i =0; i < list.size(); i++){
for(int j =0; j <list.size(); j++){
a[i][j]= list.get(j +( list.size() * i));
}
}
I managed to find "a way" to do so, knowing the number of attributes each contacts has (6). So considering an ArrayList listofContacts
int numberOfContacts = listofContacts.size()/6;
Object[][] newArrayContent = new Object[numberOfContacts][6];
for(int x = 0; x<numberOfContacts; x++){
for(int z = 0; z < 6; z++){
int y = 6 * x;
newArrayContent [x][z] = list.get(y+z);
System.out.println(newArrayContent [x][z].toString());
}
}
What you really want is to sort the ArrayList. To do that your Contacts class must implement a Comparator method.
Check the next page for an example: http://www.java-examples.com/sort-java-arraylist-descending-order-using-comparator-example
I will recommend that you parse your XML into java objects and store the object in a custom data object. This will make it easier for you to do many operations on the available data.
Here is small tutorial on how to do it.
public static String[][] convertListIntoArrayObj(List<TeamMenuSelected> possibilities) {
int numberOfColums = 2;
int numberOfRows = possibilities.size();
String[][] values = new String[numberOfRows][numberOfColums];
for(int x=0; x<possibilities.size(); x++) {
TeamMenuSelected item = possibilities.get(x);
values[x][0] = item.getTeamName();
values[x][1] = item.getTeamCuisine();
}
return values;
}
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("element_1");
arrayList.add("element_2");
arrayList.add("element_3");
arrayList.add("element_4");
int k=0;
int row = 2, col = 2;
Object[][] objArray = new Object[row][col];
for(int i = 0 ; i < row; i++) {
for(int j = 0; j < col; j++) {
objArray[i][j] = arrayList.get(k);
k++;
if(k > arrayList.size()) {
break;
}
}
}
for(int i = 0 ; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.println("Row no "+i+" col no "+j+" "+objArray[i][j] );
}
}
}
What is the most efficient way to convert data from nested lists to an object array (which can be used i.e. as data for JTable)?
List<List> table = new ArrayList<List>();
for (DATAROW rowData : entries) {
List<String> row = new ArrayList<String>();
for (String col : rowData.getDataColumn())
row.add(col);
table.add(row);
}
// I'm doing the conversion manually now, but
// I hope that there are better ways to achieve the same
Object[][] finalData = new String[table.size()][max];
for (int i = 0; i < table.size(); i++) {
List<String> row = table.get(i);
for (int j = 0; j < row.size(); j++)
finalData[i][j] = row.get(j);
}
Many thanks!
//defined somewhere
List<List<String>> lists = ....
String[][] array = new String[lists.size()][];
String[] blankArray = new String[0];
for(int i=0; i < lists.size(); i++) {
array[i] = lists.get(i).toArray(blankArray);
}
I don't know anything about JTable, but converting a list of lists to array can be done with a few lines.
For JTable in particular, I'd suggest subclassing AbstractTableModel like so:
class MyTableModel extends AbstractTableModel {
private List<List<String>> data;
public MyTableModel(List<List<String>> data) {
this.data = data;
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return data.get(0).size();
}
#Override
public Object getValueAt(int row, int column) {
return data.get(row).get(column);
}
// optional
#Override
public void setValueAt(Object aValue, int row, int column) {
data.get(row).set(column, aValue);
}
}
Note: this is the most basic implementation possible; error-checking is omitted for brevity.
Using a model like this, you don't have to worry about pointless conversions to Object[][].
Java 11 answer.
List<List<String>> table = List.of(List.of("A", "B"), List.of("3", "4"));
String[][] finalData = table.stream()
.map(arr -> arr.toArray(String[]::new))
.toArray(String[][]::new);
System.out.println(Arrays.deepToString(finalData));
[[A, B], [3, 4]]
The Collection.toArray​(IntFunction<T[]> generator) method is new in Java 11.
Of course you may also use a stream in Java 8+. Just use this mapping instead:
.map(arr -> arr.toArray(new String[0]))
(The List.of method was introduced in Java 9.)
To convert a nested list to a two-dimensional object-array, you can use this code:
public Object[][] ToObjectMatrix(List<List<String>> data) throws IllegalArgumentException {
if(data == null) {
throw new IllegalArgumentException("Passed data was null.");
}
Object[][] result = new Object[data.size()][];
for(int i = 0; i < data.size(); i++) {
result[i] = data.get(i).toArray();
}
return result;
}