create matrix of Java linked list

6 次查看(过去 30 天)
Yuval Larom
Yuval Larom 2017-3-15
回答: Saurabh 2025-5-30
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??

回答(1 个)

Saurabh
Saurabh 2025-5-30
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.

类别

Help CenterFile Exchange 中查找有关 Call Java from MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by