create matrix of Java linked list
Afficher commentaires plus anciens
Hi, I'm trying to bulid a 2D matrix, when each element in the matrix is Java Linked-list. I'm getting to following error: "Index exceeds Java array dimensions"
my code is:
n=5;
a = javaArray('java.util.LinkedList', n, n);
for i=1:n
for j=1:n
a(i,j)=java.util.LinkedList;
li(i,j)=a(i,j).listIterator;
for k=1:i*j*n
t=[i,j,i*j];
li(i,j).add(t);
end
end
end
how can i solve the problem??
Réponses (1)
Saurabh
le 30 Mai 2025
The error "Index exceeds Java array dimensions" occurs because MATLAB's 'javaArray' function creates Java arrays that are zero-based, whereas MATLAB uses one-based indexing. This mismatch can lead to indexing errors when accessing or assigning elements.
To create a 2D matrix where each element is a Java 'LinkedList', consider using a MATLAB cell array instead. Cell arrays are more flexible and align with MATLAB's indexing conventions.
Here's how to implement it:
n = 5;
a = cell(n, n); % Initialize a cell array
li = cell(n, n); % Initialize a cell array for iterators
for i = 1:n
for j = 1:n
a{i, j} = java.util.LinkedList(); % Create a LinkedList
li{i, j} = a{i, j}.listIterator(); % Create a list iterator
for k = 1:(i * j * n)
t = [i, j, i * j]; % Example data
li{i, j}.add(t); % Add data to the list
end
end
end
For more information on 'javaArray', refer to the following MathWorks official documentation:
This approach avoids indexing issues and integrates Java objects seamlessly within MATLAB's environment.
I hope this helps.
Catégories
En savoir plus sur Call Java from MATLAB dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!