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] );
}
}
}
Related
I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")
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.
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.
I am searching for the lines of code to create a new array using a method called insertRow(int[] row). With this method, users can insert 5 numbers to form an array. Then this array should be named row2. Please help.
public class App
{
public static void main(String[] args)
{
int[] row = new int[5];
int[] row1 = {2,7,1,9,4};
//int[] row2 = insertRow(row); this is wrong
}
public static void insertRow(int[] row)
{
for (int i = 0; i < row.length; i++)
{
int number;
do
number = Integer.parseInt(JOptionPane.showInputDialog("Insert the " + (i+1) + "th positif number"));
while (getal < 0);
row[i] = number;
}
}
}
You were on the right track: change the signature of your method to return int[], allocate the row inside, and put your code in place of ... below:
public static int[] insertRow() {
int[] row = new int[5];
...
return row;
}
Now this will work:
int[] row2 = insertRow(); // this is no longer wrong :)
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;
}