create matrix of Java linked list
4 views (last 30 days)
Show older comments
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??
0 Comments
Answers (1)
Saurabh
on 30 May 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.
0 Comments
See Also
Categories
Find more on Call Java from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!